如何从url字符串中获取value off参数?

时间:2016-07-28 14:52:24

标签: javascript url parameters url-parameters

链接: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');

2 个答案:

答案 0 :(得分:0)

您的代码中存在多个问题。

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
}

答案 1 :(得分:0)

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

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