只替换一个句子,并用样式包装

时间:2012-01-31 15:37:29

标签: javascript

我的目标是在html页面中找到一个句子并替换它/ wrap with <span class='red'>...</span>

基本上相同的突出显示结果的概念......但我需要突出整个句子而不是单词

由于某些原因,我的代码有时会起作用,有时候不会......

这里:

$('body').each( function () {
  $(this).html(function(i, html) {
    return html.replace(myString, '<span class="red">'+myString+'<\/span>' );
  }); 
});

当它发现句子的第一个单词的第一个出现时似乎停止了...... 有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

  • 使用正则表达式
  • 添加“g”以替换所有出现的内容
  • 使用“$ 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))