JavaScript Patterns 3.6 Regular Expression Literal
2014-06-02 12:08 小郝(Kaibo Hao) 阅读(655) 评论(0) 编辑 收藏 举报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
- 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.
- And one last note that calling RegExp() without new(as a function, not as a constructor) behaves the same as with new.
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。