Wednesday, 29 July 2015

How to get flags of RegEx in ES6

In ES5

it’s possible to get the text of the regular expression by using the source property, but to get the flag string requires parsing of toString(), such as:

 function getFlags(re) {
     var text = re.toString();
     return text.substring(text.lastIndexOf("/") + 1, text.length);
 }

 // toString() is "/ab/g"
 var re = /ab/g;

 console.log(getFlags(re));          // "g"
 

In ES6

 var re = /ab/g;

 console.log(re.source);     // "ab"
 console.log(re.flags);      // "g"
 

No comments:

Post a Comment