JavaScript Patterns 3.6 Regular Expression Literal

本文介绍了使用正则表达式字面量和构造函数创建正则表达式的方法,包括全局匹配、多行匹配和不区分大小写的匹配等特性,并对比了两者之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Using the new RegExp() constructor

// constructor

var re = new RegExp("\\\\", "gm");

2. Using the regular expression literal

// regular expression literal

var re = /\\/gm; 

when using the RegExp()constructor, you also need to escape quotes and often you need to double-escape backslashes, as shown in the preceding snippet.

 

Regular Expression Literal Syntax

• g—Global matching

• m—Multiline

• i—Case-insensitive matching 

var no_letters = "abc123XYZ".replace(/[a-z]/gi, "");

console.log(no_letters); // 123 

Another distinction between the regular expression literal and the constructor is that the literal creates an object only once during parse time.

function getRE() {

    var re = /[a-z]/;

    re.foo = "bar";

    return re;

}

var reg = getRE(),

       re2 = getRE();

console.log(reg === re2); // true 
// Kaibo(20140602): For now this result should be false in ES5(Tested in Chrome)
reg.foo = "baz"; console.log(re2.foo); // "baz" 

Note

  1. This behavior has changed in ES5 and the literal also creates new objects.  The behavior has also been corrected in many browser environments, so it’s not to be relied on.
  2. And one last note that calling RegExp() without new(as a function, not as a constructor) behaves the same as with new.

转载于:https://www.cnblogs.com/haokaibo/p/Regular-Expression-Literal.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值