首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换类中字符串中的文本+通配符号

替换类中字符串中的文本+通配符号
EN

Stack Overflow用户
提问于 2015-11-20 18:11:25
回答 1查看 996关注 0票数 2

我有一段服务器生成的html (我不能直接编辑html,所以修改必须是javascript/jquery) &我需要去掉一点文本+一个变量号,但保留所有其他内容。这是我的html:

代码语言:javascript
复制
<td>
    <font class="carttext">
        [Specifications:30][Specifications:
        <br> These are other specifications: here & here
        <br>And even more: because life is hard]
    </font>
</td>

请注意,[Specifications:30]可以是[Specifications:40][Specifications:90][Specifications:120]等,但总是以[Specifications:开头,以变量number & ]结尾

下面是我不工作但最努力的jquery:

代码语言:javascript
复制
var cartText = $(document.getElementsByClassName("carttext"));

cartText.html(function (index, html) {
    return html.replace("[Specifications:" + /[0-9]+\]/, '');
});

也曾尝试过:

代码语言:javascript
复制
var cartText = $(document.getElementsByClassName("carttext"));

cartText.html(function (index, html) {
    return html.replace("[Specifications:" + /d +\]/, '');
});

"[Specifications:"类中有多个carttext事件,所以我只想去掉字符串为"[Specificaitons:(variable number here)"的事件

更新:我不仅试图删除数字,而且还删除[Specifications:,因此:

代码语言:javascript
复制
   <font class="carttext">
   [Specifications:30][Specifications: <br> These are other
   specifications: here & here <br>And even more: because life is hard]
   </font>

变成了

代码语言:javascript
复制
   <font class="carttext">
    [Specifications:<br> These are other specifications: here & here
    <br>And even more: because life is hard]
   </font>

很抱歉之前没有指定

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-20 18:14:05

  1. 正则表达式应由/分隔。
  2. [是regex中的特殊符号,因此需要使用//进行转义。
  3. 使用g-global标志替换所有事件

在页面上加载jQuery时,请使用html(),如下所示。

代码语言:javascript
复制
$('.carttext').html(function(i, oldHtml) {
  return oldHtml.replace(/\[Specifications:\d+\]/g, '');
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<font class="carttext">
  [Specifications:30][Specifications:
  <br /> These are other specifications: here & here
  <br />And even more: because life is hard]
</font>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33833351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档