2012-02-09 125 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');