js Dynamic RegExp All In One
js Dynamic RegExp All In One
✅ js 使用 new RegExp 构造函数方式,仅支持动态创建正则表达式 regex
const name = 'abc'
// 'abc'
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
// /(^|&)abc=([^&]*)(&|$)/i
https://regexper.com/#%2F(^|%26)abc%3D([^%26]*)(%26|%24)%2Fi
❌ js 使用字面量方式,不支持动态创建正则表达式 regex
name = 'abc'
'abc'
str = `(^|&)${name}abc=([^&]*)(&|$)`;
'(^|&)abcabc=([^&]*)(&|$)'
reg = /str/i;
/str/i
vue-cli & core-js bug ("core-js": "3.6.5",)
Module not found: Error: Can't resolve 'core-js/modules/es.regexp.dot-all.js'
// 获取url中的指定参数
const getQueryString = (name) => {
// const str = `(^|&)${name}=([^&]*)(&|$)`;
// let reg = /str/i;
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return '';
};
solution
URLSearchParams
// 获取url中的指定参数
const getQueryString = (key) => {
const searchParams = new URLSearchParams(window.location.search);
return searchParams.get('code') ?? '';
};
demo
const url = `https://api.xgqfrms.xyz/user/loging?accessKey=1acd91d0065bcd5a3&redirectURL=http://10.1.130.24:8090/login&corpId=ww67cc80acd1e6&agentId=1007&code=jES94zpF7DOAEvMgKTCB5z4eBXQtJ0PZvE2FUs&state=&appid=ww675d1e6`;
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
如何使用 js 正则表达式获取匹配的变量 All In One
https://www.cnblogs.com/xgqfrms/p/14154642.html
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15572155.html
未经授权禁止转载,违者必究!