Check if URL Contains a String

Jul 12, 2023

In the browser, window.location.href contains the current URL. For example, if you open Chrome developer console on this page and type window.location.href, you'll see the following:

From there, you can use our recommended process for checking if a string contains a substring in JavaScript:

window.location.href.includes(''); // true
window.location.href.includes('foobar'); // false

Note that Internet Explorer does not support the includes() method on strings. For IE support, you should use indexOf() instead. If indexOf() returns -1, that means the substring is not present in the current URL.

window.location.href.indexOf('') !== -1; // true
window.location.href.indexOf('foobar') !== -1; // false

Other URL Components

Sometimes you don't want to test whether the whole URL contains a given string, just part of the URL. Browsers also expose some other common URL components as properties on window.location:

Using Regular Expressions

You can also test whether the current URL matches a regular expression using the string match() function as follows.

window.location.href.match(/masteringjs/) != null; // true
window.location.href.match(/foobar/) != null; // false

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials