代码如下:
<!DOCTYPE> <html lang="en"> <head> </head> <body> <body> <script> var url = 'https://www.baidu.com/s?wd=javascript&rsv_spt=1'; window.onload = function () { method2(url); }; function method1(url) { // 使用正则来 两边的参数不可能是 &=? 所以去反集[^&=?] let regex = /([^&=?]+)=([^&=?]+)/g, obj = {}; url.replace(regex, (...arg) => { obj[arg[1]] = arg[2]; }); console.log(obj); } function method2(url) { let index = url.indexOf('?'); let datas = url.substring(index+1, url.length).split('&'); let obj = {}; for (let item of datas) { let data = item.split('=') obj[data[0]] = data[1]; } console.log(obj); } </script> </html>