How to Check if URL Contains a String With JavaScript
-
Use
indexOf()
to Check if URL Contains a String - Check if URL Contains a String Using a Regular Expression
-
Use
toString().includes()
to Check if URL Contains a String
This article will teach you to check if a URL contains a string. We’ll do the checking using String.prototype.indexOf()
, Regular Expression, and String.prototype.includes()
.
Use indexOf()
to Check if URL Contains a String
When a URL contains a string, you can check for the string’s existence using the indexOf
method from String.prototype.indexOf()
. Therefore, the argument of indexOf
should be your search string.
The indexOf
method works by searching for the first occurrence of that string in the URL. Meanwhile, you’ll need to use indexOf
on window.location.href
because it contains the URL of the current web page.
In the code below, we’ve used indexOf
on window.location.href
to check if the URL contains the string 'tutorial'
.
Code:
if (window.location.href.indexOf('tutorial') > -1) {
alert('The web page contains the string \'tutorial\'');
}
Output:
Check if URL Contains a String Using a Regular Expression
You can utilize a Regular Expression pattern to search if the URL contains a string. Meanwhile, you’ll need the test()
method from RegExp.prototype.test()
.
Since you are looking for a string in the URL, the pattern to search for should be the string itself. In the code below, we’ve used the test()
method to match the string 'html'
on DelftStack’s website.
Code:
if (/html/.test(window.location.href)) {
alert('The web page contains the string \'html\'');
}
Output:
Use toString().includes()
to Check if URL Contains a String
A combination of toString()
and the includes()
method can determine if a URL contains a string. The toString()
returns a string version of an object.
So, we’ll need it because we’ll get the URL from window.location
, which is an object. Since we already have a string version of window.location
, we can use the includes()
method to determine if it contains a string.
However, the includes()
method performs a case-sensitive search, and the search for hello
will not match Hello
. In the next code block, we’ve used the includes
method and toString
to determine if the URL contains the string "google"
.
Code:
if (window.location.toString().includes('google')) {
alert('There is \'google\' in the URL');
}
Output:
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn