Fah*_*kar 6 javascript string alert indexof
以下是我所拥有的.
var myString = "http://localhost:8888/www.smart-kw.com/";
alert(myString.indexOf("localhost"));
Run Code Online (Sandbox Code Playgroud)
这给我的警告......但是如果我更改var myString = "http://localhost:8888/www.smart-kw.com/";到var myString = window.location;,这是不行的(我没有得到警报).
var myString = window.location;
alert(myString.indexOf("localhost"));
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 23
window.location是一个访问器属性,获取它的值会给你一个对象,而不是一个字符串,所以它没有一个indexOf函数.(人们有时认为它是一个字符串是完全可以理解的,因为当你设置它的值时,访问者属性的setter接受一个字符串;也就是说,window.location = "some url";实际上是有效的.但是当你得到它时,你就不会得到一个字符串.)
您可以根据需要使用window.location.toString(),, String(window.location)或window.location.href获取字符串,或使用其各种属性来检查细节.从链接,给出示例url http://www.example.com:80/search?q=devmo#test:
hash:#符号后面的URL部分,包括#符号.您可以侦听hashchange事件,以获得有关支持浏览器中哈希更改的通知.#testhost:主机名和端口号.www.example.com:80hostname:主机名(没有端口号).www.example.comhref:整个网址.http://www.example.com:80/search?q=devmo#testpathname:路径(相对于主机)./searchport:URL的端口号.80protocol:URL的协议.http:search:URL后面的部分?符号,包括?符号.?q=devmo例如,对于您引用的示例,您可以检查window.location.hostname === "localhost".