2013-03-19 117 views
1

我正在使用此search and replace jQuery腳本。 我試圖把每個字符放在一個範圍內,但它不適用於unicode字符。搜索並替換unicode字符

$("body").children().andSelf().contents().each(function(){ 
    if (this.nodeType == 3) { 
     var $this = $(this); 
     $this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>")); 
    } 
}); 

我應該改變節點類型嗎?通過什麼方式 ?

感謝

+0

你所說的「Unicode字符」意思? – 2013-03-19 14:00:58

+0

(注意:['andSelf'](http://api.jquery.com/andSelf/)是[棄用](http://api.jquery.com/andSelf/#entry-longdesc)從jQuery版本1.8開始。你應該使用['addBack'](http://api.jquery.com/addBack),這相當於,但我想他們更喜歡這個名字。) – nbrooks 2013-03-19 14:10:56

回答

1

通過替換\ W(隻字caracters) 「」 (所有caracters)

$("body").children().andSelf().contents().each(function(){ 
    if (this.nodeType == 3) { 
     var $this = $(this); 
     $this.replaceWith($this.text().replace(/(.)/g, "<span>$&</span>")); 
    } 
}) 
+2

這會使[香蕉](http:///www.fileformat.info/info/unicode/char/1f34c/index.htm)。 '「」.replace(/(.)/ g,「 $&」)'產生斷開的字符串'「 \ uD83C \ uDF4C」'。 (它已經夠了,所以SO不會讓我把所有的東西都作爲評論發佈;我必須手動編寫轉義) – 2013-03-19 14:23:41

0

匹配「的任何字符」正則表達式模式是.\w(即只匹配「字characters'-在大多數JS口味字母數字字符和下劃線[a-zA-Z0-9_])。注意.也匹配空格字符。要僅匹配和替換非空格字符,可以使用\S

有關JS RegEx語法的完整列表,請參閱the documentation

更換任何和所有的字符,讓你的正則表達式/./g

$("body").children().andSelf().contents().each(function(){ 
    if (this.nodeType == 3) { 
     var $this = $(this); 
     $this.replaceWith($this.text().replace(/(.)/g, "<span>$&</span>")); 
    } 
});