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;
};
encodeURIComponent(). Don't try to hack it yourself with string replace; it's a lot trickier than you think. This will encode spaces to%20rather than+though.%20is just as valid (in fact more valid, as it works in path components, whereas+only means a space in query components), but if you want it to look marginally prettier you can always do areplace(/%20/g, '+')afterwards of course. You might be tempted to useescape()because it does use+, but it also gets all non-ASCII characters wrong—avoid.