2013-07-19 42 views
1

我想跨度添加到特定的詞是這樣的:添加跨度特定用詞

var value = "eror"; 
var template = "/(" + value + ")/g"; 
$("#content").html($("#content").html().replace(template, '<span class="spell_error">$1</span>')); 

這是我fiddle。我嘗試使用我在這裏看到的解決方案,但似乎沒有工作。任何想法爲什麼? 謝謝

回答

6

你正在混淆正則表達式文字和字符串。

使用此創建您的正則表達式:

var template = new RegExp("(" + value + ")", 'g'); 

正則表達式文字是這樣的:

/(something)/ 

有沒有報價。但是,因爲它是一個文字,你不能用你的代碼來構建它,所以你必須使用RegExp構造函數。

一個側面說明:您更換yould做得更輕,更重要的是,通過使用html變種利用函數回調機:

$("#content").html(function(_,html){ 
    return html.replace(template, '<span class="spell_error">$1</span>') 
}); 
+0

噢噢噢,我搞砸了確實如此。謝謝!也感謝您使用回調的建議。非常感激。 – Cornwell