我正在尝试使用JavaScript修剪域名前后href
的值。例如,http://www.google.com/about-us
应修剪为www.google.com
。
var str = "http://www.google.com/about-us";
var str_before = str.replace("http://","");
document.write(str_before); // Returns ("www.google.com/about-us")
// Trim everything after the domain name
var link = str_before.substring(0, str_before.indexOf('/'));
document.write(link); // Returns "www.google.com/about-uswww.google.com"
我不知道为什么会这样。任何帮助将不胜感激!
答案 0 :(得分:2)
您看到前一个document.write
的输出与第二个document.write
的输出连接在一起。如果在输出中添加换行符,您将看到实际输出为两行,您将看到结果实际上是正确的。
尝试下面的代码段:
var str = "http://www.google.com/about-us";
var str_before = str.replace("http://","");
document.write(str_before); // Outputs "www.google.com/about-us"
// Trim everything after the domain name
var link = str_before.substring(0, str_before.indexOf('/'));
//add line break to the output
document.write( '<br />' );
//output the resulting link
document.write( link );
&#13;