简体   繁体   English

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

[英]replace all substrings in strings

Let's say I have the following string: 假设我有以下字符串:

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

How do I (with jQuery or Javascript), replace the substrings ("the", "over", "and", "into", " 's"), in that string with, let's say an underscore, without having to call str.replace("", "") multiple times? 我如何(使用jQuery或Javascript),在该字符串中替换子串(“the”,“over”,“and”,“into”,“s”),使用下划线,而不必调用str.replace(“”,“”)多次?

Note: I have to find out if the substring that I want to replace is surrounded by space. 注意:我必须找出我要替换的子字符串是否被空格包围。

Thank you 谢谢

Try with the following: 尝试使用以下内容:

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

the \\b matches a word boundary, the | \\b匹配单词边界, | is an 'or', so it'll match 'the' but it won't match the characters in 'theme'. 是'或',所以它'匹配''但它与'主题'中的字符不匹配。

The /gi flags are g for global (so it'll replace all matching occurences. The i is for case-insensitive matching, so it'll match the , tHe , THE ... /gi标志为G全球(所以它会取代所有匹配的出现次数。在i是区分大小写的匹配,所以它会匹配thetHeTHE ...

用这个。

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

Use regular expression with the g flag, which will replace all occurences: 使用带有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

Use a regular expression. 使用正则表达式。

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

The ?: is not strictly necessary, but makes the command slightly more efficient by not capturing the match. ?:不是绝对必要的,但是通过不捕获匹配使命令稍微更高效。 The g flag is necessary for global matching, so that all occurences in the string are replaced. g标志是全局匹配所必需的,因此将替换字符串中的所有出现。

I am not exactly sure what you mean by having to find out if the substring is surrounded by space. 我不确定你的意思是必须找出子串是否被空格包围。 Perhaps you mean you only want to replace individual words, and leave the whitespace intact? 也许你的意思是你只想替换单个单词,并保持空白完好无损? If so, use this. 如果是这样,请使用它。

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