parse URL with JavaScript or jQuery

11,923

Solution 1

This should work

var url = 'example.com/hello/world/20111020/';
//get rid of the trailing / before doing a simple split on /
var url_parts = url.replace(/\/\s*$/,'').split('/'); 
//since we do not need example.com
url_parts.shift(); 

Now url_parts will point to the array ["hello", "world", "20111020"].

Solution 2

You can use the jQuery-URL-Parser plugin:

var file = $.url.attr("file"); 

In your case you'd probably want to use segment():

var segments = $.url('http://allmarkedup.com/folder/dir/example/index.html').segment(); 

// segments = ['folder','dir','example','index.html']

Solution 3

   <script type="text/javascript">
    function splitThePath(incomingUrl){
     var url = document.createElement("a");
     url.href = incomingUrl;
    //url.hash  Returns the anchor portion of a URL
    //url.host  Returns the hostname and port of a URL
    //url.hostname  Returns the hostname of a URL
    //url.href  Returns the entire URL
    //url.pathname  Returns the path name of a URL
    //url.port  Returns the port number the server uses for a URL
    //url.protocol  Returns the protocol of a URL
    //url.search    Returns the query portion of a URL
    if(url.pathname && url.pathname != ""){
   var pathnameArray = url.pathname.split("/");
 }else{

}


}
</script>
Share:
11,923
chris
Author by

chris

nothing to report currently..

Updated on August 11, 2022

Comments

  • chris
    chris over 1 year

    Ok lets say I have a URL

    example.com/hello/world/20111020 (with or without the trailing slash). What I would like to do is strip from the url the domain example.com. and then break the hello world 20111020 into an array. But my other problem is. Sometimes the URL has no /hello/world/20111020 or just /hello/ so I need to first determine if there is anything after example.com if there not, then do nothing as obviously there's nothing to work with. However if there is something there for each / I need to add it to this array in order. So I can work with the array[0] and know it was hello.

    I tried something a couple days back but was running into issues with trailing slashes it kept breaking the script, I unfortunately abandoned that idea. And today I am looking for fresh ideas.