使用 jQuery 查找和替换 HTML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15203611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find and replace HTML string with jQuery
提问by Daniel
Links from the database are website titles and render on the page "Interesting Article: Author" - but occasionally the link is a question "Where's China?: GoogleMaps". The ?:
looks silly so I wanted to replace the HTML ?</span>:
with ?</span>
.
来自数据库的链接是网站标题并呈现在“有趣的文章:作者”页面上- 但有时链接是一个问题“china在哪里?:GoogleMaps”。在?:
外观愚蠢的,所以我想,以取代HTML?</span>:
用?</span>
。
Here is the jQuery I worked out:
这是我制定的jQuery:
$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');
$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');
But this doesn't actually replace it in the DOM. How do I get that string to actually change the page?
但这实际上并没有在 DOM 中替换它。如何让该字符串实际更改页面?
回答by David says reinstate Monica
I'd suggest:
我建议:
$('#relatedinfo ul li a').html(function(index,html){
return html.replace(/<\/span>(\:)/,'');
});
Or even:
甚至:
$('#relatedinfo ul li a').text(function(index,text){
return text.replace(':','');
});
An updated approach is to check that the last character in the span
is in the array of ['?','!','.']
and, if it is, then to remove the :
from the nextSibling's nodeValue:
更新的方法是检查 中的最后一个字符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(':','');
}
});
References:
参考:
回答by Henoc C. K.
You can also use regex :
您还可以使用正则表达式:
var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi');
$('#relatedinfo').html(function (i, html) {
return html.replace(rx, '<b>$&</b>')
});
source : jQuery to Find/Replace html text when not inside an html tag other than P, DIV, SPAN, TD