Javascript 替换字符串中的所有子字符串

Javascript 替换字符串中的所有子字符串,javascript,jquery,regex,Javascript,Jquery,Regex,假设我有以下字符串: var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river"; 如何(使用jQuery或Javascript)将该字符串中的子字符串(“the”、“over”、“and”、“into”、“s”)替换为下划线,而不必多次调用str.replace(“,”) 注意:我必须找出要替换的子字符串是否被空格包围 谢谢请尝试以下内容: var newString = str

假设我有以下字符串:

var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river";
如何(使用jQuery或Javascript)将该字符串中的子字符串(“the”、“over”、“and”、“into”、“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
匹配单词边界,
|
是一个“或”,因此它将匹配“the”,但不会匹配“theme”中的字符

/gi
标志是g表示全局(因此它将替换所有匹配发生的事件。
i
表示不区分大小写的匹配,因此它将匹配
使用此选项

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

使用正则表达式

str.replace(/(?:the|over|and|into)/g, '_');
严格来说,
?:
不是必需的,但是通过不捕获匹配项,使命令稍微更有效。全局匹配需要使用
g
标志,以便替换字符串中的所有出现

我不太清楚你所说的必须找出子字符串是否被空格包围是什么意思。也许你的意思是你只想替换单个单词,而保留空格不变?如果是,请使用这个

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

如果它包含
那里
,它将是
\u re
如果它包含
那里
,它将是
\u re