views:

51

answers:

3

Hi,

I have an array filled with strings, a value can for example be "not updated for > days". I use the values in the array to create some url's and need to remove the /\<> and other illegal URL characters. How do I easiest do this?

I started with

var Name0 = title[0].substring(1).replace(" ", "%20").replace("/", "") + '.aspx';
var Name1 = title[1].substring(1).replace(" ", "%20").replace("/", "") + '.aspx';
and so on but can I do this in a better way?

Thanks in advance.

+2  A: 

You could use the encodeURIComponent function which will properly URL encode the value.

Darin Dimitrov
The only way to go. (unless the OP's desire is to actually remove the offending characters to build nice-looking URLs).
Pekka
A: 

Have you had a look at encodeURIComponent?

Example usage

var encoded = window.encodeURIComponent("http://stackoverflow.com/questions/3486625/remove-illegal-url-characters-with-javascript/3486631#3486631");

// encoded contains "http%3A%2F%2Fstackoverflow.com%2Fquestions%2F3486625%2Fremove-illegal-url-characters-with-javascript%2F3486631%233486631"
Russ Cam
+2  A: 

If you wish to keep the symbols in the URI, but encode them:

encodedURI = encodeURIComponent(crappyURI);

If you wish to build 'friendly' URIs such as those on blogs:

niceURI = crappyURI.replace(/[^a-zA-Z0-9-_]/g, '');
Delan Azabani
+1 for showing both alternatives
Pekka
I just want to remove them, like with .replace("/", "") but was wondering if there's an easier way than to have a lot of .replace() on every item in an array like in my first example.
Peter
Just clump up all the symbols to kill in one: `.replace(/[bad symbols here]/g, '')`
Delan Azabani
Or, kill everything except a whitelist: `.replace([^good symbols here]/g, '')`
Delan Azabani