Regex flags i,g,m in Javascript

In this post we will see some example of regular expression to understand flags.


i (Ignore case)

Makes the regular expression search case insensitive.

const regex = /foo/i;
const str = 'FoO';

regex.test( str ); // Output true

g (Global)

This will make sure that the expression will be searched in complete string and does not stop on the first match.

const regex = /foo/g;
const str = 'foo foo bar foo';

str.match( regex ); // Output ['foo', 'foo', 'foo']

m (Multiline)

To make the regular expression work for each row we use ‘m’ flag else the complete string is considered as one rejecting rows as new line.

const regex = /foo/m;
const str = `
foo
foo
foo
`;

numberRegex.test( str ); // Output true

Conclusion

Hope this helps you to understand on how to use flags in regular expression. See you in my next post. Till then enjoy coding 🙂