2

我有这个字符串:

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() 函数可以?

4

3 回答 3

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

小提琴:http: //jsfiddle.net/uezjK/4/

于 2013-07-26T19:19:12.863 回答
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/

于 2013-07-26T19:24:17.203 回答
0

这是一个对于包含错误词子字符串的有效词(例如“still”)不会失败的示例。

http://jsfiddle.net/uezjK/1/

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)
于 2013-07-26T19:39:38.463 回答