Check if a URL is Localhost in JavaScript


Borislav Hadzhiev

Last updated: Nov 18, 2021


Photo from Unsplash

Check if a URL is Localhost in JavaScript #

To check if a url is localhost, use the includes() method to check if the string contains localhost or The includes method will return true if the url is localhost, otherwise false is returned.

function isLocalhost(url) { return url.includes('localhost') || url.includes(''); } // 👇️ true console.log(isLocalhost('http://localhost:3000/')); // 👇️ false console.log(isLocalhost(''));

We created a reusable function, which checks if a url is localhost or not.

The includes() method takes a substring and checks if it is contained in the string on which it was called.

The method returns a boolean result - true if the substring is contained in the string and false otherwise.

We used the logical OR (||) operator to chain the two calls to the includes method. If either call returns true, the isLocalhost function will also return true.

The logical OR (||) operator returns the value to the left if it's truthy, otherwise it returns the value to the right.

console.log(false || true); // 👉️ true console.log(true || false); // 👉️ true console.log(false || false); // 👉️ false
The includes method is not supported in Internet Explorer. If you have to support the browser, use the indexOf method instead.

To check if a url is localhost, call the indexOf() method on the url, checking if the strings localhost or are contained in the url. If the indexOf method returns -1 for both strings, the url is not localhost.

// supported in IE function isLocalHost(url) { return url.indexOf('localhost') !== -1 || url.indexOf('') !== -1; } // 👇️ true console.log(isLocalHost('http://localhost:3000/')); // 👇️ false console.log(isLocalHost(''));

The String.indexOf method returns the index of the first occurrence of a substring in a string.

If the substring is not contained in the string, the method returns -1.

If either of the calls to the indexOf method returns an index that is not equal to -1, we can conclude that the url is localhost.

Using the indexOf method is a bit more indirect and harder to read, however it gets the job done if you need to support Internet Explorer.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.