xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何使用 js 正则表达式获取匹配的变量 All In One

如何使用 js 正则表达式获取匹配的变量 All In One

$0 ~ $9

js regexp group & RegExp.$0 ~ RegExp.$9 All In One

https://www.cnblogs.com/xgqfrms/p/16169157.html

// 只有使用构造函数 RegExp, 才可以动态使用变量创建正则表达式

const str = 'abcabcabc';

const set = new Set();

for (let s of str) {
    set.add(s)
}

let keys = '';

for (let k of set.keys()) {
    keys += k;
}


// const reg = /`${keys}`/g;
// /`${keys}`/g ❌

const reg = new RegExp(keys, 'g');

// const len = str.replaceAll(reg, '')

const len = str.replace(reg, '')

const str = "pattern";

const reg = new RegExp(str, "ig");

https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression

https://stackoverflow.com/questions/4029109/javascript-regex-how-to-put-a-variable-inside-a-regular-expression

refs

js 使用 RegExp 构造函数方式,仅支持动态创建正则表达式 regex

https://www.cnblogs.com/xgqfrms/p/15572155.html



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-12-18 14:12  xgqfrms  阅读(964)  评论(7编辑  收藏  举报