【问题标题】:how to get the value off parameter from the url string?如何从 url 字符串中获取参数的值?
【发布时间】:2016-12-03 01:16:21
【问题描述】:

链接:http://yaezde.localhost/machen/mach-den-impfcheck/question=2

我知道如何使用 window.location.href 获取整个 url;但之后我想知道获取问题参数值的正则表达式是什么。

答案:var question=2

我已经尝试过此代码..但不适用于我的场景

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var foo = getParameterByName('question');

【问题讨论】:

  • 函数 getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[[]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"), results = regex.exec(url);如果(!结果)返回空值; if (!results[2]) return '';返回 decodeURIComponent(results[2].replace(/\+/g, " ")); }

标签: javascript url parameters url-parameters


【解决方案1】:

与其重新发明轮子,我建议使用现有的库,例如 https://github.com/Mikhus/domurlhttps://medialize.github.io/URI.js

这些库的 API 应该易于使用,并且已经过测试。

【讨论】:

    【解决方案2】:

    您的代码中有几个问题。

    function getParameterByName(name, url) {//note parameter url
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
      var regex = new RegExp("[?&\\/](" + name + "=([^&#]*))(?:&|#|$)");
      //                         ^^^ ^ in your example /question=2
            results =regex.exec(url);
      console.log(results);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    
    var url='http://yaezde.localhost/machen/mach-den-impfcheck/question=2'
    var foo = getParameterByName('question', url);//include url in arguments or it will be undefined in the function
    console.log(foo);
    
    //Another way to access url in the function scope
    function getParameterByName(name){
       //get url from global scope if exists
       var url = url || window.location.href;
       //other things
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 2012-07-13
      • 2020-11-28
      • 1970-01-01
      • 2020-06-12
      • 2010-10-14
      相关资源
      最近更新 更多