Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/450.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript从IndexOf创建子字符串不工作_Javascript - Fatal编程技术网

JavaScript从IndexOf创建子字符串不工作

JavaScript从IndexOf创建子字符串不工作,javascript,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:/”,“”); 文件。写(str_before);//返回(“www.google.com/about-us”) //删除域名后的所有内容 var link=str_before

我正在尝试使用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:/”,“”);
文件。写(str_before);//返回(“www.google.com/about-us”)
//删除域名后的所有内容
var link=str_before.substring(0,str_before.indexOf('/');

文档。写入(链接);//返回“www.google.com/about uswww.google.com”
您看到的是前一个
文档的输出。write
与第二个
文档的输出连接在一起。write
。如果在输出中添加换行符,您将看到实际输出为两行,并且您将看到结果实际上是正确的

请尝试下面的代码段:

var str=”http://www.google.com/about-us";
var str_before=str.replace(“http:/”,“”);
文件。写(str_before);//输出“www.google.com/about us”
//删除域名后的所有内容
var link=str_before.substring(0,str_before.indexOf('/');
//在输出中添加换行符
文件。写入(“
”); //输出结果链接
文件。编写(链接)
var a=document.createElement(“a”);a、 href=str;a、 主机;//“www.google.com”
不,这是
文档。写
欺骗你。使用
console.log
检查代码的结果。不要使用document.write,忘记它的存在。为什么初学者课程教人们使用它,它不再是90/00了。@epascarello不仅是一些课程,甚至MDN示例也经常使用
dw()
。几年前我给Mozilla留下了关于在示例中使用
dw()
的反馈,但不确定它的使用是否减少了。谢谢!我忽略了我放在那里的document.write()行。