0

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.

4
  • stackoverflow.com/questions/2849415/… Commented Feb 21, 2016 at 16:08
  • 1
    I think you might be looking at stackoverflow.com/questions/901115/… Commented Feb 21, 2016 at 16:09
  • do you need to get the value of tag_id? Commented Feb 21, 2016 at 16:13
  • FYI params in the URL, starting with ? are available as location.search Commented Feb 21, 2016 at 16:16

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

I should note that this will work for urls where 'tag_id' is not the last (or only) attribute passed by the URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.