有这么一个需求,判断URL是不是包含from参数,如果只是简单粗暴得用indexOf判断它是不是包含这个字符串,可能会有个问题,比如要求的参数是from=push,但是要是参数是afromb=,也会判定为true,这个是不符合逻辑的,所以应该用正则来处理这个看似简单的需求。
错误示例:
if (window.location.search.substr(1).indexOf('from') !== -1)
正确姿势:
getQueryString(name) {
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
const r = window.location.search.substr(1).match(reg)
console.log('r' + r)
if (r != null) return decodeURIComponent(r[2])
return null
}