LinMinquan's Blog

Experience technology to change life

js解析url

解析 URL Params 为对象,例如 ‘http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled’

parseParam(url)

/* 结果
{
    user: 'anonymous',
    id:[123, 456], // 重复出现的 key 要组装成数组,能被转成数字的就转成数字类型
    city: '北京', // 中文需要解码
    enabled: true, // 未指定值的 key 约定为 true 
}
*/
let testUrl = 'http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled';

function parseParam(url) {
    let urlObject = new URL(url);
    let result = {};
    let user = urlObject.searchParams.get("user");
    if ( user != 'null') {
        result.user = user; 
    };
    let id = urlObject.searchParams.getAll("id");
    if ( id != 'null' ) {
        result.id = id;
    }
    let city = urlObject.searchParams.get("city");
    if( city != 'null' ) {
        result.city = city;
    }
    let enabled = urlObject.searchParams.get("enabled");
    if( enabled === '' ) {
        result.enabled = true;
    } else {
        result.enabled = enabled;
    }

    return result;
}

let test233 = parseParam(testUrl);
console.log(test233);

才注意到 js 里有个专门用来处理 url 的 object, URL

 


Share