How to parse URL using javascript
How to parse URL using javascript
In certain cases you may want to parse a URL using javascript, although I don’t specifically recommend this, rather you should use a php approach, server side. Javascript can be manipulated and if passing the URL somewhere and then actually doing work with the result, you may have surprises in the end …
But for static functions that you just need to show the result in browser, it should be safe enough.
Scenario
1 2 |
# We'll take a link from one of my previous articles var url = "http://www.yourhowto.net/how-to-strip-spaces-out-of-a-string-in-perl/" |
I used a static variable for this example as we just want to show you the actual parsing of this url.
Solution
The solution is to use the split function from javascript.
1 2 |
var url_array = url.split("/"); console.log(url_array); |
Output
1 2 |
Array[5] ["http:", "", "www.yourhowto.net", "how-to-strip-spaces-out-of-a-string-in-perl", ""] |
Once you have this array, you can start and use the elements in your little script.
Combine elements in a javascript array
To combine the elements of the array, you would need to use the the join function from javascript:
1 2 |
var url_purge = url_array[0]+"//"+url_array[2]+"/"+url_array.slice(-2).join('/'); console.log(url_purge); |
The output will be:
1 |
http://www.yourhowto.net/how-to-strip-spaces-out-of-a-string-in-perl/ |
Again, rather then using this in a ajax call for instance, better send the full url and parse the url sent in php, it is safer like that!