Take a look at the window.location docs , the information you want is in location.search
, so a function to check it could just be:
function url_has_vars() {
return location.search != "";
}
質問
I am using this code to detect the homepage and it works great:
var url= window.location.href;
if(url.split("/").length>3){
alert('You are in the homepage');
}
My problem is that I also need to detect if the url has variables for example:
mysite.com?variable=something
I need to also detect if the url has variables on it too
How can I do this?
解決 3
Take a look at the window.location docs , the information you want is in location.search
, so a function to check it could just be:
function url_has_vars() {
return location.search != "";
}
他のヒント
Using window.location.pathname
could work too:
if ( window.location.pathname == '/' ){
// Index (home) page
} else {
// Other page
console.log(window.location.pathname);
}
You can find out if you're on the homepage by comparing href to origin:
window.location.origin == window.location.href
To get the query parameters you can use the answer here: How can I get query string values in JavaScript?
if current url is xxxxx.com something like that, then xxx
if (window.location.href.split('/').pop() === "") {
//this is home page
}
You need a query string searching function to do this..
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Before redirect check the query string and match with the expected value and redirect as requirement.
Taking inspiration from Mataniko suggestion, I slightly modified it to fix its issue:
if (window.location.origin + "/" == window.location.href ) {
// Index (home) page
...
}
In this way, this test pass only in homepage