码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 3.6 Regular Expression Literal

时间:2014-06-02 15:50:52      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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.

bubuko.com,布布扣
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" 
bubuko.com,布布扣

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.

JavaScript Patterns 3.6 Regular Expression Literal,布布扣,bubuko.com

JavaScript Patterns 3.6 Regular Expression Literal

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/haokaibo/p/Regular-Expression-Literal.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!