【问题标题】:trying to split a url into an array like http:,www.,stackoverflow,questions,ask试图将一个 url 拆分成一个数组,如 http:,www.,stackoverflow,questions,ask
【发布时间】:2019-12-26 03:44:10
【问题描述】:

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

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

【问题讨论】:

  • 请添加更多关于您想要完成的任务的详细信息。你说它会“输出字符串 ok”,但你现在到底卡在什么地方了?
  • 我需要将字符串转换为数组,具体取决于人输入的网站。我刚刚使用了 stackoverflow 和一个例子,它可以是任何 url。

标签: javascript html css arrays url


【解决方案1】:
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"]

【讨论】:

    【解决方案2】:

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

    window.location 指向您正在使用的当前窗口/选项卡。这意味着:您不能通过 window.location 在站点 example.com 上使用 stackoverflow.com。您可以改用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]);

    【讨论】:

    • 这不接受输入的内容,只是使用了这个 url
    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多