我有这个字符串:
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()函数会做什么?
答案 0 :(得分:7)
使用正则表达式并替换:
var errors = ["Altough", "stil", "kdi"];
var regExp = new RegExp('\\b('+errors.join('|')+')\\b', 'gi');
var text = text.replace(regExp, '<span class="error">$1</span>');
答案 1 :(得分:0)
除了Karl-Andre的回答,这里有一种没有正则表达式的方法(只是为了给你一个不同的前景):
var text = "Altough I am the eldest son, they stil see me as kdi.";
var errors = ["Altough", "stil", "kdi"];
for (var i = 0; i < errors.length; i++) {
var content = errors[i];
text = text.replace(content, "<span class='error'>" + content + "</span>");
}
这也是一个小提琴:http://jsfiddle.net/azMVk/
答案 2 :(得分:0)
这是一个有效单词没有失败的例子,这些单词的子字符串是错误单词(例如“仍然”)。
var text = "Altough I am the eldest son, they stil see me as kdi. But I am still a kid.";
var tokens = text.split(/\s+/);
var errors = ["Altough", "stil", "kdi"];
var html = "";
for (var i=0; i<tokens.length; i++) {
var word = tokens[i].replace(/\W+/, '');
if ($.inArray(word, errors) >= 0) {
html += "<span class='error'>" + tokens[i] + "</span> ";
} else {
html += tokens[i] + " ";
} }
$('body').append(html)