本文翻译自:Replace all spaces in a string with '+' [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
I have a string that contains multiple spaces. 我有一个包含多个空格的字符串。 I want to replace these with a plus symbol. 我想用加号替换它们。 I thought I could use 我以为我可以用
var str = 'a b c';
var replaced = str.replace(' ', '+');
but it only replaces the first occurrence. 但它只取代了第一次出现。 How can I get it replace all occurrences? 如何让它替换所有出现的?
参考:https://stackoom.com/question/FvEN/用-替换字符串中的所有空格-复制
Do this recursively: 递归地执行此操作:
public String replaceSpace(String s){
if (s.length() < 2) {
if(s.equals(" "))
return "+";
else
return s;
}
if (s.charAt(0) == ' ')
return "+" + replaceSpace(s.substring(1));
else
return s.substring(0, 1) + replaceSpace(s.substring(1));
}
Use global search in the string. 在字符串中使用全局搜索。 g flag g标志
str.replace(/\s+/g, '+');
source: replaceAll function source: replaceAll函数
In some browsers 在某些浏览器中
(MSIE "as usually" ;-)) (MSIE“通常”;-))
replacing space in string ignores the non-breaking space (the 160 char code). 替换字符串中的空格会忽略不间断的空格(160字符代码)。
One should always replace like this: 一个人应该总是这样替换:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation: 很好的详细解释:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/ http://www.adamkoch.com/2009/07/25/white-space-and-character-160/
You can also do it like 你也可以这样做
str = str.replace(/\s/g, "+");
Have a look to the fiddle 看看小提琴
You need the /g
(global) option, like this: 你需要/g
(全局)选项,如下所示:
var replaced = str.replace(/ /g, '+');
You can give it a try here . 你可以在这里尝试一下 。 Unlike most other languages, JavaScript, by default, only replaces the first occurrence. 与大多数其他语言不同,默认情况下,JavaScript仅替换第一次出现的语言。