Javascript 尝试将url拆分为一个数组,如http:、www、、stackoverflow、questions、ask
输入工作正常,它将输出字符串ok,但我在创建数组方面太差了,我只是不知道以后该怎么做,因为我到处都找了,还没有找到一种方法Javascript 尝试将url拆分为一个数组,如http:、www、、stackoverflow、questions、ask,javascript,html,css,arrays,url,Javascript,Html,Css,Arrays,Url,输入工作正常,它将输出字符串ok,但我在创建数组方面太差了,我只是不知道以后该怎么做,因为我到处都找了,还没有找到一种方法 <body> <form> <fieldset> <legend> Url: </legend> <input type="url" ID="inputurl" value="please input a
<body>
<form>
<fieldset>
<legend>
Url:
</legend>
<input type="url" ID="inputurl" value="please input a URL">
<input type="button" onclick="PlaceUrl()" value="try me">
</fieldset>
</form>
<p id="URLdemo"></p>
<script>
function PlaceUrl() {
var x = document.getElementById("inputurl").value;
document.getElementById("URLdemo").innerHTML = x;
//outputs the string fine
var x = string.split(window.location.pathname);
var x = str.array (window.location.pathname.split(x));
//this does nothing
}
</script>
网址:
函数PlaceUrl(){
var x=document.getElementById(“inputurl”).value;
document.getElementById(“URLdemo”).innerHTML=x;
//输出字符串
var x=string.split(window.location.pathname);
var x=str.array(window.location.pathname.split(x));
//这没用
}
您可以使用构造函数来处理它
window.location
指向您正在使用的当前窗口/选项卡。这意味着:您不能通过window.location
在example.com网站上使用stackoverflow.com。您可以改用URL()
var url=新url('https://stackoverflow.com/questions/59483624/trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask#');
log('Host:',url.Host);
log('Path name:',url.pathname);
log('Question id:',url.pathname.split('/')[2]);
log('Question title:',url.pathname.split('/')[3])代码>请添加有关您试图完成的任务的更多详细信息。你说它会“输出字符串ok”,但你现在到底在搞什么?我需要字符串转换成数组,这取决于输入的人放在哪个网站上。我刚刚使用了stackoverflow,举个例子,它可以是任何url。这不需要输入什么,只需要使用这个url
var href = 'https://stackoverflow.com/questions/59483624/trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask'
var arr = href.split(/[\.\\\/]/g)
console.log(arr)
// ["https:", "", "stackoverflow", "com", "questions", "59483624", "trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask"]