如何解决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>
这是控制台的结果
服务器是Tomcat(但我觉得与服务器无关)。代码在 Windows 10 中运行。
更新 2
更新代码以打印 window.location.href
的类型。这是更新后的代码:
var url = window.location.href;
console.log(url + "," + (typeof url) + "," + url.startsWith('http://127.0.0.1'));
这是打印输出:
类型是字符串。
更新 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/
匹配。看这个截图
更新 5
这似乎是“gulp + 浏览器同步”的问题。我停止了这个工具并在端口 3000 上重新启动了 Tomcat。然后 url.startsWith('http://127.0.0.1')
按预期为 http://127.0.0.1:3000
返回 true。谜团已解(关于导致此问题的原因)。
如果您从事前端工作,我强烈建议您使用此工具。很酷。
最终更新
此问题已解决,它是由我用于开发工作的 gulp + 浏览器同步 引起的。你可以在这篇文章中看到更新,看看它是如何被发现的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。