2015-11-20 98 views
2

我有一块服务器生成的html(我不能直接编辑html,所以修改必须是javascript/jquery)&我需要去掉一个文本+ a可变数字,但留下一切。这里是我的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:启动,并与可变数字结尾& ]

这是我的非工作,但-best省力的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 +\]/, ''); 
}); 

我在carttext"[Specifications:"出现了多次,所以我只是想在字符串"[Specificaitons:(variable number here)"

UPDATE剥离的发生:我试图剥离不只是数量,但也[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

'html.replace(/ \ [规格:\ S * \ d + \] /克, '');'。 'g'是一个全局标志 - 允许regex多次匹配字符串。 – jperezov

+0

您不能合并字符串和正则表达式。这是你的问题。 – epascarello

回答

2
  1. 正则表达式应该由/
  2. [分隔为正则表达式的特殊符号,所以还需要通过/
  3. 使用g -global标志前进行转义替换所有出现

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

+0

在桌面上很好用,但似乎无法在手机上使用。是否还需要添加其他内容才能使其与移动设备兼容? – KateTheGreat

+0

@KateTheGreat也应该在手机上工作。我没有看到移动浏览器不支持的代码中的任何内容。您能否使用远程调试在控制台中看到错误? – Tushar