window.location.href 和 startsWith

问题描述

我在 Chrome 中运行了以下 JavaScript(仅限演示)

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

如果 url 是 http://127.0.0.1 并且 startsWith 按预期返回 true。但是,如果网址是

http://127.0.0.1:3000

startsWith 返回 false。有人知道为什么吗?

另一方面,如果我有这个:

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

startsWith 按预期返回 true。

当url为http://127.0.0.1:3000时,如何让startsWith为以下代码返回true

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

更新 1

这是完整的代码

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

这是控制台的结果

enter image description here

服务器是Tomcat(但我觉得与服务器无关)。代码在 Windows 10 中运行。

更新 2

更新代码以打印 window.location.href 的类型。这是更新后的代码

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

这是打印输出

enter image description here

类型是字符串。

更新 3

我之所以使用 3000 端口是因为我使用“gulp + browsersync”来查看我的页面的外观,而 3000 是 browsersync 的认端口。这可能是个问题吗?

更新 4

尝试了以下代码显示是否有任何隐藏字符。

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

仍然得到假 url.startsWith('http://127.0.0.1')。共 22 个字符,与 http://127.0.0.1:3000/ 匹配。看这个截图

enter image description here

更新 5

这似乎是“gulp + 浏览器同步”的问题。我停止了这个工具并在端口 3000 上重新启动了 Tomcat。然后 url.startsWith('http://127.0.0.1') 按预期为 http://127.0.0.1:3000 返回 true。谜团已解(关于导致此问题的原因)。

如果您从事前端工作,我强烈建议您使用此工具。很酷。

最终更新

此问题已解决,它是由我用于开发工作的 gulp + 浏览器同步 引起的。你可以在这文章中看到更新,看看它是如何被发现的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)