javascript 纯正则按需拿到url里的参数,兼容hash

直接上代码吧

var getParmasByKey = (url = location.href, key='') => (url.match(new RegExp(('([&?])'+key+'=([^&#]*)')))||[])[2]
var url = 'http://localhost/test?name=wind&id=50012&age=27&test=&dd=22&cc=#first'

console.log(getParmasByKey(url, 'name'))
console.log(getParmasByKey(url, 'id'))
console.log(getParmasByKey(url, 'age'))
console.log(getParmasByKey(url, 'test'))
console.log(getParmasByKey(url, 'dd'))
console.log(getParmasByKey(url, 'cc'))

你可能感兴趣的:(javascript,正则表达式)