View Full Version : How do i replace a space in a string with a +?
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 :)
requestcode
08-27-2002, 01: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:
http://developer.netscape.com/docs/manuals/js/client/jsguide/regexp.htm
beetle
08-27-2002, 04: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
Thanks guys, the link works OK now. Much appreciated :)
whammy
08-28-2002, 12: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,"+");
;)
adios
08-28-2002, 12:34 AM
Hmm....
escape(var);
http://www.devguru.com/Technologies/ecmascript/quickref/escape.html
whammy
08-28-2002, 01: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...
joh6nn
08-28-2002, 05: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,"+");
beetle
08-28-2002, 01: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
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.