Issue #201 (RegExp properties, JS Libs, Testing, Data)05/25/17
A regular expression object, or RegExp, has a number of different methods and properties available to it. The most common ones are probably the exec() and test() methods. But as shown in the following code block, there are some interesting properties that you might not be familiar with:
let myRegExp = /example/ig;
// The flags property
console.log(
myRegExp.flags
); // "gi"
// The global property
console.log(
myRegExp.global
); // true
let myRegExp2 = /example/i;
console.log(
myRegExp2.global
); // false
// The source property
let myRegExp3 = /([A-Z])/g;
console.log(
myRegExp3.source
); // "([A-Z])"
// The multiline property
let myRegExp4 = /([A-Z])/m;
console.log(
myRegExp4.multiline
); // true
|
JS Bin demo
In the code I've used five different properties available to gain info from a regular expression object. As many of you might know, using flags is a common technique when constructing regular expressions. In four of the five examples, I've used properties related to flags.
The
flags property, for example, allows me to list the flags used. Notice they come back in alphabetical order, rather than in the order used in the regular expression. Each of the other three flags examples return a Boolean to tell me if that specific flag was used.
Finally, the one non-flags property I used is the
source property. This one returns a string that contains the source text of the regular expression object.
Browser support for these is mostly good, with some exceptions. You can get more info on these on the
MDN page on the RegExp object, and from there you can view the individual articles to see browser support.
Now on to this week's tools!