使用jQuery查找并替换HTML字符串

来自数据库的链接是网站标题,并在“ 有趣的文章 :作者”页面上呈现 – 但有时链接是一个问题“ 哪里是中国? :GoogleMaps”。 ?:看起来很傻,所以我想替换HTML ?:?

这是我制定的jQuery:

$('#relatedinfo ul li a').html().replace('?:','?');

但这实际上并没有在DOM中取代它。 如何让该字符串实际更改页面?

我建议:

 $('#relatedinfo ul li a').html(function(index,html){ return html.replace(/<\/span>(\:)/,''); }); 

JS小提琴演示 。

甚至:

 $('#relatedinfo ul li a').text(function(index,text){ return text.replace(':',''); }); 

JS小提琴演示 。

更新的方法是检查范围中的最后一个字符是否为['?','!','.']数组,如果是,则从nextSibling的nodeValue中删除:

 $('#relatedinfo ul li a span').text(function(index,text){ var lastchar = text.split('').pop(); if (['?','!','.'].indexOf(lastchar) > -1) { this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(':',''); } }); 

JS小提琴演示 。

参考文献:

  • html()
  • String.replace()
  • text()

你也可以使用正则表达式:

 var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi'); $('#relatedinfo').html(function (i, html) { return html.replace(rx, '$&') }); 

source: jQuery在不在P,DIV,SPAN,TD之外的html标记内查找/替换html文本