首页 > 解决方案 > 试图将 url 拆分成一个数组,如 http:,www.,stackoverflow,questions,ask

问题描述

输入工作正常,它会输出字符串,但我在创建数组方面很糟糕,我只是不知道该怎么做,我到处看了看,还没有找到办法。

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

标签: javascripthtmlcssarraysurl

解决方案


您可以使用URL()构造函数来处理它。

window.location指向您正在使用的当前窗口/选项卡。这意味着:您不能在站点 example.com 上通过window.location. 你可以URL()改用。

var url = new URL('https://stackoverflow.com/questions/59483624/trying-to-split-a-url-into-an-array-like-http-www-stackoverflow-questions-ask#');

console.log('Host:', url.host);
console.log('Path name:', url.pathname);
console.log('Question id:', url.pathname.split('/')[2]);
console.log('Question title:', url.pathname.split('/')[3]);


推荐阅读