Javascript 只替换一个句子出现的地方,并用风格将其包装起来
我的目标是在html页面中找到一个句子,并用Javascript 只替换一个句子出现的地方,并用风格将其包装起来,javascript,Javascript,我的目标是在html页面中找到一个句子,并用 … 基本上,突出显示结果的概念是一样的……但我需要突出显示整个句子,而不是单词 出于某种原因,我的代码有时有效,有时无效 在这里: $('body')。每个(函数(){ $(this).html(函数(i,html){ 返回html.replace(myString,“+myString+”); }); }); 当它发现句子的第一个单词第一次出现时,它似乎停止了。。。 有什么帮助吗?好的,让我们试试这个,使用递归: var html = $('b
…
基本上,突出显示结果的概念是一样的……但我需要突出显示整个句子,而不是单词
出于某种原因,我的代码有时有效,有时无效
在这里:
$('body')。每个(函数(){
$(this).html(函数(i,html){
返回html.replace(myString,“+myString+”);
});
});
当它发现句子的第一个单词第一次出现时,它似乎停止了。。。
有什么帮助吗?好的,让我们试试这个,使用递归:
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))
- 使用regexp
- 添加“g”以替换所有发生的事件
- 使用“$1”重复使用字符串
- 小心字符串中没有特殊字符(可能会被误认为是regexp运算符)
var re=new Regexp(“(“+myString+”)”,“g”); html.replace(关于“$1”)
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))
var re = new Regexp('('+myString+')', "g");
html.replace(re, '<span class="red">$1<\/span>')