JavaScript创建IndexOf中的子字符串不起作用

时间:2016-12-29 17:21:24

标签: javascript

我正在尝试使用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"

我不知道为什么会这样。任何帮助将不胜感激!

1 个答案:

答案 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;
&#13;
&#13;