我有一段服务器生成的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:开头,以变量&]结尾
下面是我不工作但尽最大努力的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>

很抱歉之前没有指定

最佳答案

正则表达式应以/分隔
[是regex中的特殊符号,因此需要在/
使用g-全局标志替换所有出现的事件
当jQuery加载到页面上时,使用html()如下。

$('.carttext').html(function(i, oldHtml) {
  return oldHtml.replace(/\[Specifications:\d+\]/g, '');
});

<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>

10-06 07:37