查找和使用jQuery替换HTML字符串(Find and replace HTML string

2019-07-20 23:19发布

从数据库的链接是网站标题和渲染页面“ 有趣的文章 :作者” -但偶尔的联系是一个问题,“ 在哪里中国? :谷歌地图”。 的?:看起来很傻,所以我想替换HTML ?</span>:?</span>

这里是我摸索出了jQuery:

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

但是,这实际上并不在DOM更换。 如何获取该字符串实际更改的页面?

Answer 1:

我建议:

$('#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提琴演示 。

更新的方法是检查的最后一个字符span是阵列中['?','!','.']如果是的话,删除:从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()


Answer 2:

您还可以使用正则表达式:

var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi');

$('#relatedinfo').html(function (i, html) {
   return html.replace(rx, '<b>$&</b>')
});

来源: jQuery来查找/替换HTML文本时不超过P,DIV,SPAN,TD以外的HTML标记内



文章来源: Find and replace HTML string with jQuery