JavaScript - 替换 html 字符串中的特定单词索引 [英] JavaScript - Replace specific word index in html string
问题描述
我在 JS 字符串操作方面有一个具有挑战性的任务:有一个 HTML 字符串,我需要在其中替换特定单词索引处的单词.词索引是忽略HTML标签时的词数.
I have a challenging mission in JS string manipulation: There is a HTML string in which I need to replace a word at a specific word index. The word index is the number of the word when ignoring the HTML tags.
例如,这里是 HTML 字符串:
For example, here is the HTML string:
<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 个单词(即单词时间):<span style="color:red;">times</span>
The task is to replace word number 2 in the html (which is the word times) with the text: <span style="color:red;">times</span>
所以最终的 HTML 字符串应该是:
So the final HTML string should be:
<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>
对这个挑战有什么想法吗?
Any ideas for this challenge?
推荐答案
我会先通过标记过滤的 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 ? ;)
这篇关于JavaScript - 替换 html 字符串中的特定单词索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!