2016-07-28 59 views
-1

鏈接:http://yaezde.localhost/machen/mach-den-impfcheck/question=2如何從url字符串中獲取value off參數?

我知道如何使用window.location.href獲取整個網址;但之後比我想知道什麼是正則表達式來獲取問題參數值。

答案:VAR問題= 2

我已經試過這code..but不是我的工作情況

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'); 
+0

function getParameterByName(name,url)if(!url)url = window.location.href; (= [[&&] *)| name = name.replace(/ [\ [\]]/g,「\\ $ &"); var regex = new RegExp(」[?&]「+ name +」如果(!results)返回null; if(!results [2])return''; return decodeURIComponent(results [2]。); results = regex.exec(url); 替換(/ \ +/g,「」)); } –

+0

但不起作用 –

+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 
} 
相關問題