且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript - 替换 html 字符串中的特定单词索引

更新时间:2023-11-15 14:46:46

我会先通过标记过滤的 HTML 来找到这个词,然后进行替换.

I would first find the word by tokenizing the filtered HTML, and then do the replacement.

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

Let's start from your string :

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>'
});

演示

情况 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
});

演示

情况 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;
  })
});

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

Can you spot why the second one was tricky ? ;)