powerdong / myProblems

我用到了,你可能用到
0 stars 1 forks source link

原生JS获取地址栏携带的参数 #13

Open powerdong opened 4 years ago

powerdong commented 4 years ago

当跳转页面需要携带参数时,我们通常会将所需参数通过URL地址携带过去,而在新页面如何获取携带过来的参数也是一个问题,接下来我们实现一种方法用来获取相关的参数

// eg: https://www.baidu.com/s?wd=lambda
/*
* @param {String} name 需要获取的参数名称
*/
function getQuery(name) {
        // 编写正则表达式获取到这一段字符
        var reg = new RegExp("(^|[&?]{1})" + name + "=([^&]*)(|$)", "i");
        // r = {0: "?wd=lambda" ,1: "?",2: "lambda",3: "",index: 23,input: "https://www.baidu.com/s?wd=lambda"}
        var r = window.location.search.match(reg);
        if (r != null) return decodeURIComponent(r[2]);
        return null;
    };
powerdong commented 4 years ago
const getTargetSearch = function(key){
    let url = location.search;
    let result = '';
      if (url.indexOf("?") != -1) {
          let str = url.substr(1);
          let strs = str.split("&");
        for(let i = 0; i<strs.length; i++){
        let obj = strs[i].split('=');
        if(obj[0] == key){
          result = obj[1];
          return result;
        }
      }
      }
      return result;
}