...

View Full Version : Converting URL to string



Max Power
06-30-2004, 06: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
"http://www.domain.com/Another%20Site%20Name"
from "http://www.domain.com/Another Site Name" ??

Any ideas??? :eek:

sad69
06-30-2004, 07: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:
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm#how

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

Good luck,
Sadiq.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum