Check if a URL is Localhost in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20212 min read

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 127.0.0.1. The includes method will return true if the url is localhost, otherwise false is returned.

index.js
function isLocalhost(url) { return url.includes('localhost') || url.includes('127.0.0.1'); } // ๐Ÿ‘‡๏ธ true console.log(isLocalhost('http://localhost:3000/')); // ๐Ÿ‘‡๏ธ false console.log(isLocalhost('http://example.com'));

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.

index.js
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 127.0.0.1 are contained in the url. If the indexOf method returns -1 for both strings, the url is not localhost.

index.js
// supported in IE function isLocalHost(url) { return url.indexOf('localhost') !== -1 || url.indexOf('127.0.0.1') !== -1; } // ๐Ÿ‘‡๏ธ true console.log(isLocalHost('http://localhost:3000/')); // ๐Ÿ‘‡๏ธ false console.log(isLocalHost('http://example.com'));

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee