繁体   English   中英

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

[英]replace all substrings in strings

假设我有以下字符串:

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匹配单词边界, | 是'或',所以它'匹配''但它与'主题'中的字符不匹配。

/gi标志为G全球(所以它会取代所有匹配的出现次数。在i是区分大小写的匹配,所以它会匹配thetHeTHE ...

用这个。

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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM