我有一块服务器生成的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>
很抱歉没有先前指定
答案 0 :(得分:2)
/
[
是正则表达式中的特殊符号,因此需要通过前面的/ g
- 全局标记来替换所有出现次数在页面上加载jQuery时,请使用html(),如下所示。
$('.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;