简体   繁体   中英

I need to run a function if the URL has a specific string that can also come up as part of another string using jQuery or Javascript

I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.

var location = window.location.href; 
if (location.indexOf("?page=1") > -1){
//Do something
};
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {

}

?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:

function unparam(qs) {
    var params = {},
        e,
        a = /\+/g,
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); };

    while (e = r.exec(qs)) {
        params[d(e[1])] = d(e[2]);
    }

    return params;
}

var urlParams = unparam(window.location.search.substring(1));

if(urlParams['page'] == '1') {
    // code here
}

Alternatively, a regex with word boundaries would have worked:

if(/\bpage=1\b/.test(window.location.search)) {
    // code here
}

You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:

  var index = location.indexOf("?page=1"); //Returns the index of the string
  var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
  //Unicode values for 0-9 is 48-57, check if number lies within this range

Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.

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