在 正则表达式基础 这篇文章中,我们介绍过正则表达式的两种创建方式:
1.字面量创建方式(两个斜杆之间包起来的,都是用来描述规则的元字符)
let reg1 = /\d+/
2.构造函数模式创建 (两个参数:元字符字符串,修饰字符串)
let reg2 = new RegExp("\\d+")
区别:
(1)构造函数因为传递的是字符串,\需要写两个才表示\
reg = /\d+/g
reg = new RegExp("\\d+","g")
(2)两个斜杠中间包起来的都是元字符,如果正则中包含某个变量的值,则不能使用字面量方式创建,需要使用构造函数模式
let type = "tanjia"
reg = /^@"+type+"@$/
console.log(reg.test("@tanjia@")) /* false */
console.log(reg.test('@""""typeeeeee"@')) /*true*/
这种情况只能使用构造函数方式,因为它传递的规则是字符串,只有这样才能进行字符串拼接
let type = "tanjia"
reg = new RegExp("^@"+ type +"@$")
console.log(reg.test("@tanjia@")) /* true */
另:常用的正则表达式文章:常用正则表达式