简体   繁体   中英

Get value from url with javascript

I have a programmes page which contains tags and subcategories. On clicking a tag, the url of the page changes to something like this:

localhost:3000/programmes/global-entrances/gre?tag_id=2&url=%2Ftag_sort%2F2%3Fcategory%3Dgre

Based on which tag has been clicked I want to change the tag color, so I need to get the tag_id value from the url.

First I checked whether the url contains a string called tag_id by doing this.

$(document).ready(function(){
    var url      = window.location.href; 
    substring = "tag_id";
    if(url.indexOf(substring) > -1){
          // if true then get the tag_id value 
    }
});

Now I got stuck with it.

Here is the shortcut to get the value of tag_id .

 $(document).ready(function(){ var url = "localhost:3000/programmes/global-entrances/gre?tag_id=2&url=%2Ftag_sort%2F2%3Fcategory%3Dgre";//window.location.href; var result = url.split("?")[1].split("&")[0].split("=")[1]; alert(result); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

A jsfiddle link , test it.

This is only the quick and shortcut solution, if its work for you then let me know.

We need our good old friend RegEx for this.

First, we get the url of the page by doing document.location.href. This will give you the URL of the page, and for off-site testing purposes you can replace 'document.location.href' with the URL as a string.

The regex tests for 'tag_id=', any characters, then the ampersand which connects the next value. Then we strip 'tag_id=' from the result, and slice off the end '&' - leaving you with the value at the end.

    var url = document.location.href;
    var regEx = /(tag_id=).+?&/g;
    var value = (url.match(regEx));
    value = value[0].replace("tag_id=", "");
    value = value.slice(0, -1);
    console.log(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM