Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS获取url参数的方法 #52

Open
artdong opened this issue Nov 22, 2019 · 1 comment
Open

JS获取url参数的方法 #52

artdong opened this issue Nov 22, 2019 · 1 comment
Labels
js javascript

Comments

@artdong
Copy link
Collaborator

artdong commented Nov 22, 2019

JS获取url参数的方法

@artdong artdong added the js javascript label Nov 22, 2019
@artdong artdong changed the title JS获取url参数 JS获取url参数的方法 Nov 22, 2019
@artdong
Copy link
Collaborator Author

artdong commented Dec 2, 2019

1、循环

function getQuery() {
    const url = decodeURI(location.search); // 获取url中"?"符后的字串(包括问号)
    let query = {};
    if (url.indexOf("?") != -1) {
        const str = url.substr(1);
        const pairs = str.split("&");
        for(let i = 0; i < pairs.length; i ++) {
             const pair = pairs[i].split("=");
            query[pair[0]] = pair[1];
        }
    }
    return query ;  // 返回对象
}

function getQueryVariable(name) {
    const url = decodeURI(location.search); // 获取url中"?"符后的字串(包括问号)
    let query = {};
    if (url.indexOf("?") != -1) {
        const str = url.substr(1);
        const pairs = str.split("&");
        for(let i = 0; i < pairs.length; i ++) {
             const pair = pairs[i].split("=");
             if(pair[0] === name) return  pair[1]; // 返回 参数值
        }
    }
   return(false);
}

2、正则表达式

function  getQueryVariable(name) {
      const reg = new RegExp("(^|&)" + name+ "=([^&]*)(&|$)", "i");
      const result = window.location.search.substr(1).match(reg);
      if ( result != null ){
         return decodeURI(result[2]);
     }else{
         return null;
     }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js javascript
Projects
None yet
Development

No branches or pull requests

1 participant