2012-02-09 138 views
3

比方說,我有以下字符串:替換所有子字符串中

var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river"; 

如何(用jQuery或Javascript),更換子(下稱「」,「超過」,「和」,「到「,」s「),在那個字符串中,讓我們說下劃線,而不必多次調用str.replace(」「,」「)?

注意:我必須找出我要替換的子字符串是否被空格包圍。

謝謝

回答

8

嘗試用以下:

var newString = str.replace(/\b(the|over|and|into)\b/gi, '_'); 
// gives the output: 
// _ quick brown fox jumped _ _ lazy dog _ fell _ St-John's river 

\b單詞邊界匹配,|是「或者」,所以它會匹配「的」,但它不會匹配'主題'中的字符。

/gi標誌爲G全球(所以它會取代所有匹配的出現次數,該i是區分大小寫的匹配,所以它會匹配thetHe,...了`

1

使用此。

str = str.replace(/\b(the|over|and|into)\b/gi, '_'); 
+0

如果它包含了'there',這將是'_re' – epascarello 2012-02-09 15:27:15

+0

@epascarello - 是多數民衆贊成正確的,修改了它的感謝。 – ShankarSangoli 2012-02-09 15:31:57

0

使用正則表達式與g標誌,將取代所有出現:

var str = "The quick brown fox jumped over the lazy dog and fell into the river"; 
str = str.replace(/\b(the|over|and|into)\b/g, "_") 
alert(str) // The quick brown fox jumped _ _ lazy dog _ fell _ _ river 
+1

如果它包含'there',那麼'_re' – epascarello 2012-02-09 15:27:25

+0

好點,修復它。 – 2012-02-09 15:28:29

0

使用正則表達式。

str.replace(/(?:the|over|and|into)/g, '_'); 

?:不是嚴格必需的,但使該命令稍微更有效的通過不捕獲匹配。 g標誌對於全局匹配是必需的,以便替換字符串中的所有匹配項。

我不確定你的意思是要找出子字符串是否被空間包圍。也許你的意思是你只想替換單詞,並保持空格不變?如果是這樣,使用這個。

str.replace(/(\s+)(?:the|over|and|into)(\s+)/g, '$1_$2'); 
相關問題