比方說,我有以下字符串:替換所有子字符串中
var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river";
如何(用jQuery或Javascript),更換子(下稱「」,「超過」,「和」,「到「,」s「),在那個字符串中,讓我們說下劃線,而不必多次調用str.replace(」「,」「)?
注意:我必須找出我要替換的子字符串是否被空格包圍。
謝謝
比方說,我有以下字符串:替換所有子字符串中
var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river";
如何(用jQuery或Javascript),更換子(下稱「」,「超過」,「和」,「到「,」s「),在那個字符串中,讓我們說下劃線,而不必多次調用str.replace(」「,」「)?
注意:我必須找出我要替換的子字符串是否被空格包圍。
謝謝
嘗試用以下:
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
是區分大小寫的匹配,所以它會匹配the
,tHe
,...了`
使用此。
str = str.replace(/\b(the|over|and|into)\b/gi, '_');
使用正則表達式與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
如果它包含'there',那麼'_re' – epascarello 2012-02-09 15:27:25
好點,修復它。 – 2012-02-09 15:28:29
使用正則表達式。
str.replace(/(?:the|over|and|into)/g, '_');
的?:
不是嚴格必需的,但使該命令稍微更有效的通過不捕獲匹配。 g
標誌對於全局匹配是必需的,以便替換字符串中的所有匹配項。
我不確定你的意思是要找出子字符串是否被空間包圍。也許你的意思是你只想替換單詞,並保持空格不變?如果是這樣,使用這個。
str.replace(/(\s+)(?:the|over|and|into)(\s+)/g, '$1_$2');
如果它包含了'there',這將是'_re' – epascarello 2012-02-09 15:27:15
@epascarello - 是多數民衆贊成正確的,修改了它的感謝。 – ShankarSangoli 2012-02-09 15:31:57