Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove illegal URL characters with JavaScript

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.

like image 881
Peter Avatar asked Aug 15 '10 07:08

Peter


2 Answers

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, ''); 
like image 129
Delan Azabani Avatar answered Sep 17 '22 17:09

Delan Azabani


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

like image 43
Darin Dimitrov Avatar answered Sep 17 '22 17:09

Darin Dimitrov