我的目标是在html页面中找到一个句子并替换它/ wrap with
<span class='red'>...</span>
基本上相同的突出显示结果的概念......但我需要突出整个句子而不是单词
由于某些原因,我的代码有时会起作用,有时候不会......
这里:
$('body').each( function () {
$(this).html(function(i, html) {
return html.replace(myString, '<span class="red">'+myString+'<\/span>' );
});
});
当它发现句子的第一个单词的第一个出现时似乎停止了...... 有什么帮助吗?
答案 0 :(得分:1)
小心你的字符串中没有特殊的字符(可以将它作为正则表达式运算符)
var re = new Regexp('('+myString+')', "g");
html.replace(re, '<span class="red">$1<\/span>')
答案 1 :(得分:0)
好的,让我们尝试一下,使用递归:
var html = $('body').html();
function replaceHTML(haystack, needle, replacement, position){
var index = haystack.indexOf(needle);
var newHaystack = haystack.replace(needle, replacement);
if(index > - 1){
return replaceHTML(newHaystack, needle, replacement, index);
} else {
return haystack;
}
}
$('body').html(replaceHTML($('body').html(), 'string you want to replace', 'replacement string', 0))