2013-07-26 141 views
2

替換句子的話,我有這個字符串:帶格式的HTML

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的替換()函數將做什麼?

+1

你或許應該拆分句子翻譯成令牌,然後再評估每個令牌,然後建立起自己的註解HTML字符串。這樣你就不會輕易受到子串問題的困擾。 –

回答

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/

+1

這會將包含errors數組的單詞標記爲子字符串。例如,在「仍然」中,「stil」將被標記,這可能不是OP想要的。 –

+0

[@Chris is correct](http://jsfiddle.net/davidThomas/uezjK/2/);但是,在光明的一面:['\ b'可以幫助](http://jsfiddle.net/davidThomas/uezjK/3/)。 –

+0

@ChrisFarmer謝謝指出它,改變了表達! –

0

除了卡爾·安德烈的回答,這裏是沒有正則表達式的方式(只給你一個不同的準):

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/

0

這裏有一個例子,對於有錯誤詞(例如「仍然」)的子字符串的有效詞不會失敗​​。

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)