View Full Version : Converting URL to string

Max Power
06-30-2004, 07:44 PM
I am trying to convert a URL to a string. I am having problems with URL's that have spaces (" ") in them. Basically, I would like to replace any space in a URL with "%20". Here is an example:

http://www.domain.com/Site Name

I can convert this to a string like this:
strURL = "http://www.domain.com/Site Name";
strNewUrl = strUrl.replace(" ", "%20");
return (strNewURL); // returns "http://www.domain.com/Site%20Name"

However, if there are MULTIPLE spaces in the original URL, I don't know how to find and replace ALL of the spaces with a '%20'.

So, what would be the best way to have a function return
from "http://www.domain.com/Another Site Name" ??

Any ideas??? :eek:

06-30-2004, 08:14 PM
You're on the right track, check this out:

var strURL = "http://www.domain.com/Site Name Goes Here";
var re = new RegExp ("\\s", 'g') ; // \s means white space (the extra \ is an escape), g means global
var strNewURL = strURL.replace(re, "%20");
alert(strNewURL); // returns "http://www.domain.com/Site%20Name"

I was going to suggest using escape(), but that doesn't work for ':' (like http://...).

You may want to checkout this website and take a look at the source:

It's pretty complicated, but it's probably full-proof if that's what you're looking for.

Good luck,