2016-12-29 46 views
2

我试图修剪使用JavaScript的域名前后href的值。例如,http://www.google.com/about-us应修整为www.google.comJavaScript从IndexOf创建子字符串不起作用

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

'VAR一个=使用document.createElement( “A”); a.href = str;一个举办方; //“www.google.com”' – 2016-12-29 17:23:39

+1

不,它是'document.write'欺骗你。使用'console.log'来检查你的代码的结果。 – Teemu

+2

不要使用document.write,忘记它存在。为什么初学者课程教人们使用它,它不再是90/00s。 – epascarello

回答

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);

+0

谢谢!我忽略了我已有的document.write()行。 –