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

时间:2015-11-20 18:11:25

标签: jquery html regex

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

<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:开头,并以变量编号&amp; ]

这是我的非工作但最好的努力jquery:

var cartText = $(document.getElementsByClassName("carttext"));

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

也尝试过:

var cartText = $(document.getElementsByClassName("carttext"));

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

我在"[Specifications:"课程中出现过多次carttext,所以我只是试图去掉字符串为"[Specificaitons:(variable number here)"

的位置

更新:我试图不只是删除号码,而是[Specifications:,所以:

   <font class="carttext">
   [Specifications:30][Specifications: <br> These are other
   specifications: here & here <br>And even more: because life is hard]
   </font>

变为

   <font class="carttext">
    [Specifications:<br> These are other specifications: here & here
    <br>And even more: because life is hard]
   </font>

很抱歉没有先前指定

1 个答案:

答案 0 :(得分:2)

  1. 正则表达式应由/
  2. 分隔
  3. [是正则表达式中的特殊符号,因此需要通过前面的/
  4. 进行转义
  5. 使用g - 全局标记来替换所有出现次数
  6. 在页面上加载jQuery时,请使用html(),如下所示。

    &#13;
    &#13;
    $('.carttext').html(function(i, oldHtml) {
      return oldHtml.replace(/\[Specifications:\d+\]/g, '');
    });
    &#13;
    <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>
    &#13;
    &#13;
    &#13;