简体   繁体   中英

JavaScript REGEX extend `/pattern/` with custom functions

I know I can do this...

RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend()

I want to extend regex patterns in this format: /pattern/ , so I can do...

/pattern/.xtend()

Edit: It was a problem with syntax

Turns out it was a missing semi-colon. I need a semi-colon before the regex pattern otherwise it gives syntax error.

Thanks for all the comments. Works great now.

Turns out it was a missing semi-colon. I need a semi-colon before the regex pattern otherwise it gives syntax error.

I was running this in Firebug console, which automatically returns the value of the last line... but because there is no semi-colon after the third line, and the fourth starts with a regex, it was getting an error.

RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend()
/pattern/.xtend()

Adding the semi-colon solves the problem...

RegExp.prototype.xtend = function(){ console.log(123) }
y = new RegExp(/pattern/)
y.xtend(); // <~~ this semi-colon fixes the issue
/pattern/.xtend()

Thanks for all the comments. Works great now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM