You will need this if you are working on a web site that depends on data extracted from the URL. You can extract or read URL parameters at the Server side in Asp.Net (such as using QueryString) and using JavaScript methods at the client side itself.
Whether you are using jQuery or JavaScript for your frontend, you can simply use the indexOf() method with the href property using windows.location object.
Syntax for indexOf()
string.indexOf(searchvalue)
The method indexOf() returns the position (a number) of the first occurrence of a given string. It will return -1, if it finds nothing that matches the given string.
You can use the indexOf() method with href property of windows.location object. For example,
var t = window.location.href.indexOf('&book=');
If the method finds the string &book= in the URL, it will return the location (a number) and the location to the variable t.
Note: The character & indicates that I am passing an extra parameter to the URL.
Now, let's see an example.
I wish to check if the URL contains the parameter ?book= in jQuery. My script would be …
if (window.location.href.indexOf('?book=') > 0) {
// ... do something
}
Here’s a complete Markup with the Script to check using jQuery.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<input id="bt" type="button" value="Check URL" />
</body>
<script>
$(document).ready(function () {
$("#bt").on("click", function () {
if (window.location.href.indexOf('?book=') > 0) {
console.log("The URL contains ?book");
}
});
});
</script>
</html>
Using JavaScript
If you are using JavaScript, you’ll simply call a function using the button’s clicks event. For example
<input id="bt" type="button" onclick="checkUrl()" value="Check URL" />
<script>
function checkUrl() {
if (window.location.href.indexOf('?book=') > 0) {
console.log("The URL contains ?book");
}
}
</script>
In my next post, I have shared an example explaining how to replace a given string with another string in the URL bar using JavaScript or jQuery.
Thanks for reading. ☺