【问题标题】:JavaScript - Replace specific word index in html stringJavaScript - 替换 html 字符串中的特定单词索引
【发布时间】:2013-09-06 14:01:36
【问题描述】:

我在 JS 字符串操作方面有一个具有挑战性的任务: 有一个 HTML 字符串,我需要在其中替换特定单词索引处的单词。单词索引是忽略 HTML 标记时单词的编号。

例如,这里是 HTML 字符串:

<span style="font-family:Times New Roman;">At times like this I don't know what to
do. Other times I have no problem.</span>

任务是将html中的第2个单词(即单词times)替换为文本:&lt;span style="color:red;"&gt;times&lt;/span&gt;

所以最终的 HTML 字符串应该是:

<span style="font-family:Times New Roman;">At <span style="color:red;">times</span> 
like this I don't know what to do. Other times I have no problem.</span>

对这个挑战有什么想法吗?

【问题讨论】:

  • 你想替换所有出现的那个词还是只替换第一个?

标签: javascript html string replace


【解决方案1】:

我会先通过对过滤后的 HTML 进行标记来找到单词,然后进行替换。

让我们从你的字符串开始:

var html = '<span style="font-family:Times New Roman;">At times like this don\'t know what to do. Other times I have no problem.</span>';

案例1,你想替换所有出现的:

var tokens = html.replace(/<[^>]*>/g,'').split(/\W+/).filter(Boolean);
var newHTML = html.replace(new RegExp('\\b'+tokens[1]+'\\b', 'g'), function(s){
     return '<span style="color:red;">'+s+'</span>'
});

Demonstration

案例2,你只想替换指定索引处的单词(这个出奇的棘手):

var tokens = html.replace(/<[^>]*>/g,'').split(/\W+/).filter(Boolean);
var wordToReplaceIndex = 1, wordToReplace = tokens[wordToReplaceIndex];
var occIndex = 0;
for (var i=0; i<wordToReplaceIndex; i++) {
   if (tokens[i]===wordToReplace) occIndex++;
}
i=0;
var newHTML = html.replace(new RegExp('\\b'+wordToReplace+'\\b', 'g'), function(s){
    return (i++===occIndex) ? '<span style="color:red;">'+s+'</span>' : s
});

Demonstration

案例 2 的替代解决方案:

var i=0, wordToReplaceIndex = 1;
var newHTML = html.replace(/>([^<]+)</, function(txt) {
  return txt.replace(/\w+/g, function(s) {
    return i++==wordToReplaceIndex ? '<span style="color:red;">'+s+'</span>' : s;
  })
});

你能看出为什么第二个很棘手吗? ;)

【讨论】:

  • 您的解决方案只替换第一次出现,不确定它们是否是要求。
  • 在问题的示例中,它是第一次出现。要替换所有出现,只需添加 g 标志。
  • 我明白了,只是让 OP 意识到,他/她的问题可能是一个错误 :)
  • 我仍在尝试理解您的代码,但无论如何,您在“案例 2”中的解决方案效果很好。我不太了解正则表达式,所以我不知道为什么它很棘手:) 非常感谢!
【解决方案2】:
var html = '<span style="font-family:Times New Roman;">At times like this don\'t know what to do. Other times I have no problem.</span>';
var tokens = html.replace("Times","<span style="color:red;">times</span>");

【讨论】:

  • 最好解释代码而不是转储。它有助于教育那些在未来找到答案的人!
【解决方案3】:

我一直在使用这个 jQuery 插件来替换/编辑 DOM 中任何部分的文本。完整的正则表达式支持非常有用且易于使用

http://benalman.com/projects/jquery-replacetext-plugin/

【讨论】:

    【解决方案4】:

    我认为一个不错的解决方案是拆分和替换然后加入。这是一个例子:

    <div id="replace-me">Hello, world</div>
    

    replaceWordAtIndex = function (text, index, replacement) { 
        text = text.split(' ');
        text[index] = replacement;
        text = text.join(' ');
        return text;
    }
    
    wrapWordAtIndex = function (text, index, before, after) { 
        text = text.split(' ');
        text[index] = before + text[index] + after;
        text = text.join(' ');
        return text;
    }
    
    var obj = document.getElementById('replace-me');
    obj.innerText = replaceWordAtIndex(obj.innerText, 1, 'Universe');
    obj.innerHTML = wrapWordAtIndex(obj.innerText, 1, '<b>', '</b>');
    

    应该导致:

    <div id="replace-me">Hello, <b>Universe</b></div>
    

    这里有一个JSFiddle for you 来查看它的实际应用

    【讨论】:

      【解决方案5】:
      function smartReplace(str,index,strReplace){
      
          var wStart=0,wEnd=0;
          var startInd=str.indexOf(">")+1;    
          var wc=0;
          for(i=startInd;i<str.length;i++)
          {
              if (str.charAt(i) == ' ')
              {
                  wc=wc+1;
                  if (wc==index) 
                  {   
                      wEnd=i-1;
                      break;
                  }
                  wStart=i+1;
              }
          }
      
          var newString = str.substring(0,wStart) + strReplace + str.substring((wEnd +1),(str.length-1));
          document.write(newString);
      }
      

      > 如下调用 smartReplace()

      var str1="<span style=\"font-family:Times New Roman;\">At times like this I don't know what to do. Other times I have no problem.</span>)";
      smartReplace(str1,3,"<span style=\"color:red;\">times</span>");
      

      【讨论】:

      • 谢谢,这很好,但是我正在寻找一个可以在字符索引未知时替换特定单词的功能。例如“替换字号 2”。
      猜你喜欢
      • 1970-01-01
      • 2011-04-13
      • 2012-09-14
      • 2012-06-02
      • 2011-10-20
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多