We can use jQuery to see if the URL contains a word or parameter by using window.location, the href property, and the indexOf() method.
if( window.location.href.indexOf("wordWeWantToCheck") > -1) {
//Do something
}
To see if the URL contains a word we first need to get the url of the current page we are on. We do this by using window.location. We then need to get the href property of window.location. This will return the current url of the page.
Once we have the url of the page, we can check it for our word using the indexOf() method. In the code above, the word we are looking for is, wordWeWantToCheck.
Finally, we put this in an if else conditional statement so that if the word we want is in the URL, we do one thing, and if it is not, we do something else.
Let’s see this example in action below.
How to Get the Current URL and see if it Contains any Word
We will have 2 steps in this example. In the first step, we will get the current URL of the page. We will store it as a string.
In the second step, we will let the user input any characters or word they want. We will then check to see if that is contained in our URL. The current url of this page is: https://daztech.com/using-jquery-to-see-if-url-contains/.
Here is our HTML set up:
Check if the String above is in the current url: https://daztech.com/using-jquery-to-see-if-url-contains/
Check URL
In the JavaScript code, we will first get the url as we did in the first part using the window.location object and the href property.
Once we have the URL, we will need to get the string the user has entered using the val() method. We will then use the indexOf() method to check if this string is contained in our URL.
We will finally let the user know if the string is contained in the URL by using the text() method.
Here is the JavaScript code:
$('.click-me').click(function(){
//Get the current URL
var url = window.location.href;
//Get the user input
var userString = $("#textInput").val();
//Check if User string is in URL
if( url.indexOf(userString) > -1 ){
$("#result").text(userString + " IS in the URL above");
} else {
$("#result").text(userString + " is NOT in the URL above");
}
});
The final code and output for this example is below:
Code Output:
Check if the String above is in the current url:
https://daztech.com/using-jquery-to-see-if-url-contains/
Full Code:
Check if the String above is in the current url: https://daztech.com/using-jquery-to-see-if-url-contains/
Check URL
Hopefully this article has been useful to help you understand how to use jQuery to see if URL Contains a certain string.