Replace all spaces in a string with '+'
JavascriptStringJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
Here's an alternative that doesn't require regex:
var str = 'a b c';
var replaced = str.split(' ').join('+');
Solution 2 - Javascript
You need the /g
(global) option, like this:
var replaced = str.replace(/ /g, '+');
You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.
Solution 3 - Javascript
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
Solution 4 - Javascript
Solution 5 - Javascript
Solution 6 - Javascript
Use a regular expression with the g
modifier:
var replaced = str.replace(/ /g, '+');
From Using Regular Expressions with JavaScript and ActionScript:
> /g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.
Solution 7 - Javascript
You need to look for some replaceAll option
str = str.replace(/ /g, "+");
this is a regular expression way of doing a replaceAll.
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Solution 8 - Javascript
NON BREAKING SPACE ISSUE
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
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/
Solution 9 - Javascript
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));
}