Vitaminaq / interview-collection

前端面试合集
3 stars 0 forks source link

URL参数格式化,转JSON,请把url链接:https://www.mingyuanyun.com?address=sz&people=&industry=it#123456789 转换为如下格式 #1

Open Vitaminaq opened 2 years ago

Vitaminaq commented 2 years ago
{
origin: 'https://www.mingyuanyun.com',
hash: '123456789',
address: 'sz',
people: '',
industry: 'it'
}
Vitaminaq commented 2 years ago
// api解法
function urlFormat(url) {
    let u = {};
    try {
        u = new URL(url);
    } catch(e) {
        throw Error('请传入正确的url');
    }
    let obj = {};
    obj.origin = u.origin;
    obj.hash = u.hash.replace('#', '');

    const usp = new URLSearchParams(u.search.replace('?', ''));
    const p = Object.fromEntries(usp);
    return JSON.stringify(Object.assign(obj, p), null, 0);
}