如何从url字符串中获取参数off的值

how to get the value off parameter from the url string?

本文关键字:获取 参数 off 的值 字符串 url      更新时间:2023-09-26

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

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

答案:var问题=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');

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

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
}

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

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