window.location.href and startsWith

1.3k views Asked by At

I have the following JavaScript running in Chrome (demo only)

var url = window.location.href;
console.log(url + ": " + url.startsWith('http://127.0.0.1'));

If the url is http://127.0.0.1 and the startsWith returns true as expected. However, if the url is

http://127.0.0.1:3000

startsWith returns false. Anybody knows why?

On the other hand, if I have this:

var url= "http://127.0.0.1:3000"; //straight string
console.log(url + ": " + url.startsWith('http://127.0.0.1'));

startsWith returns true as expected.

How to make startsWith return true for the following code when url is http://127.0.0.1:3000

   var url = window.location.href;
   console.log(url + ": " + url.startsWith('http://127.0.0.1'));

Update 1

This is the complete code:

<head>
    <script>
        var url = window.location.href;
        console.log(url + ", " + url.startsWith('http://127.0.0.1'));
    </script>
</head>

This is the result in Console

enter image description here

The server is Tomcat (but I don't feel it is server related). The code runs in Windows 10.

Update 2

Updated code to print the type of window.location.href. Here is the updated code:

var url = window.location.href;
console.log(url + ", " + (typeof url) + ", " + url.startsWith('http://127.0.0.1'));

Here is the printout:

enter image description here

The type is string.

Update 3

The reason why I am using port 3000 is because I use "gulp + browsersync" to see how my page looks like and 3000 is the default port of browsersync. Could this be an issue?

Update 4

Tried the following code to reveal whether there is any hidden characters.

var url = window.location.href;
console.log(url + ", " + (typeof url) + ", " + url.startsWith('http://127.0.0.1'));
console.log(Array.from(url).map(c => c.charCodeAt(0)));

Still got false url.startsWith('http://127.0.0.1'). Total of 22 characters, which matches http://127.0.0.1:3000/. See this screenshot

enter image description here

Update 5

It seems to be the issue of the "gulp + browser sync". I stopped this tool and restarted Tomcat at port 3000. Then url.startsWith('http://127.0.0.1') returns true as expected for http://127.0.0.1:3000. The mystery is resolved (about what caused this issue).

If you do front-end work, I strongly recommend using this tool. Very cool.

Final Update

This issue is resolved and it was caused by gulp + browser sync I use for dev work. You can see the updates in this post to see how it was found to be the cause.

0

There are 0 answers