Anjan Dutta
Check if URL contains string in javascript
Check if URL contains string in javascript
Published On: 28/10/2021
To check if URL contains any given string in javascript we can use the indexOf
method.
At first we have to get the current URL using this code window.location.href
.
Then we will find the given string usein below method.
This solution will work in ES5 and above.
if(window.location.href.indexOf('any-given-string') > -1) { // string found} else { // not found}
Or using the includes
method, we can also check like below.
This solution works only in ES6 and above.
if(window.location.href.includes('any-given-string') === true) { // string found} else { // not found}
Thanks for reading.