【问题标题】:Getting a part from the page URL从页面 URL 获取一部分
【发布时间】:2023-03-23 01:07:01
【问题描述】:

我有一个网址:

http://example.com/lobby/5(5 可以是任意数字)。

如何将 5 部分转换为 JS var?

链接是页面url,不是用户提交的。

当链接为http://example.com/lobby.php?id=5时,我有这个功能可以工作

function getQueryParam(param) {
  location.search.substr(1).split("&").some(function(item) { // returns first occurence and stops
      return item.split("=")[0] == param && (param = item.split("=")[1])
    })
  return param;
}

【问题讨论】:

    标签: javascript url hyperlink


    【解决方案1】:

    只使用正则表达式

    var link = "http://example.com/lobby.php?id=5";
    var numb = link.match(/\=([^=/]+)\/?$/)[1];
    console.log(numb) // 5
    
    var link1 = "http://example.com/lobby/55";
    var numb1 = link1.match(/\/([^\/]+)\/?$/)[1];
    console.log(numb1) // 55
    <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

    【讨论】:

      【解决方案2】:
        window.location.search.match(/[0-9]+/);
      

      从 url 获取任意数字。

      【讨论】:

        猜你喜欢
        • 2021-11-23
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2013-03-16
        相关资源
        最近更新 更多