View Full Version : How do i replace a space in a string with a +?

08-27-2002, 01:45 PM
I am trying to link to a site called Mapquest directly via a URL. To do this, the spaces in the variables need to be changed to + signs, and i'm not really good enough to go through all that. I was wondering if someone had a script or could suggest somewhere to find one that would do this. Thanks all :)

08-27-2002, 02:38 PM
A combination of a Regular Expression and string.replace() would do the job. Here is an example:
re1=/ /gi
myvar1=" "
myvar2=myvar1.replace(re1, "+")

Here is some info on how they work:

08-27-2002, 05:34 PM
Very true requestcode, but isn't that a waste of variable space? Why not just this?
var myvar1="this and this";
myvar1 = myvar1.replace(/ /g, "+");And the 'i' modifier isn't necessary, since spaces only have 1 case :D

08-27-2002, 09:42 PM
Thanks guys, the link works OK now. Much appreciated :)

08-28-2002, 01:27 AM
I know just typing a space works, but isn't this more "correct"?:

var myvar1="this and this";
myvar1 = myvar1.replace(/\s/g,"+");


08-28-2002, 01:34 AM



08-28-2002, 02:32 AM
Duh... adios is right... I'm still thinking in vbscript (and not well at that! hehe since you could use Server.URLEncode(var) in VBScript...).

escape(var) is what you should use...

08-28-2002, 06:06 AM
i don't think so. D2K2 needs +'s, not %20's. i think this is still the right way to go:

var myvar1="this and this";
myvar1 = myvar1.replace(/\s/g,"+");

08-28-2002, 02:29 PM
Whammy - well, perhaps

\s is the same as [ \t\v\n\r\f]

so \s will also replace tabs, vertical tabs, newlines, carriage returns, and formfeeds. So \s would be accurate if D2K2 intends to replace all those with +'s as well.

Being that this is a URL, it's likely that spaces will be the only whitespace characters present anyhow. I just wanted to point out the difference.

If it makes you feel better you can always go with /[ ]/g :D