前端问号参数的获取函数的封装

queryURLParams是项目中一个非常常用的方法,在这里就把这个函数放在string的原型上,供调用此方法。

  • 1.字符串截取处理
String.prototype.queryURLParams = function queryURLParams(attr) {
    let self = this,
        obj = {};
   let askIndex = self.indexOf('?'),
        wellIndex = self.indexOf('#'),
        askText = '',
        wellText = '';
    askIndex === -1 ? askIndex = self.length : null;
    wellIndex === -1 ? wellIndex = self.length : null;
    if (askIndex < wellIndex) {
        askText = self.substring(askIndex + 1, wellIndex);
        wellText = self.substring(wellIndex + 1);
    } else {
        askText = self.substring(askIndex + 1);
        wellText = self.substring(wellIndex + 1, askIndex);
    }
    // 井号获取信息了
    if (wellText) obj['HASH'] = wellText;
    // 问号获取信息了
    if (askText) {
        askText.split('&').forEach(item => {
            let [key, value] = item.split('=');
            obj[key] = value;
        });
    }

    return typeof attr === "undefined" ? obj : (obj[attr] || '');
};

let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0
  • 2.利用A元素对象的相关属性「OOP」
String.prototype.queryURLParams = function queryURLParams(attr) {
    // A元素对象:hash/host/hostname/pathname/protocol/search...
    // 基于这些私有属性即可获取到URL中每一部分的信息
    let link = document.createElement('a');
    link.href = self;
    let {
        search,
        hash
    } = link;
    link = null;
    if (hash) obj['HASH'] = hash.substring(1);
    if (search) {
        search.substring(1).split('&').forEach(item => {
            let [key, value] = item.split('=');
            obj[key] = value;
        });
    }

    return typeof attr === "undefined" ? obj : (obj[attr] || '');
};

let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0
  • 3.直接正则处理
String.prototype.queryURLParams = function queryURLParams(attr) {
    let reg1 = /([^?&=#]+)=([^?&=#]+)/g,
        reg2 = /#([^?&=#]+)/g;
    self.replace(reg1, (_, key, value) => obj[key] = value);
    self.replace(reg2, (_, hash) => obj['HASH'] = hash);

    return typeof attr === "undefined" ? obj : (obj[attr] || '');
};

let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0

你可能感兴趣的:(前端问号参数的获取函数的封装)