我有这个字符串:
var text = "Altough I am the eldest son, they stil see me as kdi.";
这个数组:
var errors = ["Altough", "stil", "kdi"];
我想替换数组中句子中的单词,因此文本如下所示:
<span class="error">Altough</span> I am the eldest son, they <span class="error">stil</span> see me as <span class="error">kdi</span>.
我必须使用正则表达式吗?还是 JavaScript 的 Replace() 函数就可以?
最佳答案
使用正则表达式并替换:
var errors = ["Altough", "stil", "kdi"];
var regExp = new RegExp('\\b('+errors.join('|')+')\\b', 'gi');
var text = text.replace(regExp, '<span class="error">$1</span>');
fiddle :http://jsfiddle.net/uezjK/4/
关于javascript - 将句子中的单词替换为格式化的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889225/