Regular Expression Flag | JavaScript Tutorial
RegExp.prototype.test()
It accepts a string that we test against a regular expression and returns either trueor falseRegExp.prototype.exec()
let regex = /hello/;
let str = 'hello world';
let result = regex.test(str);console.log(result);
// returns 'true' as hello is present in our string
RegExp.prototype.exec()
receive an array of all the matched groups. It accepts a string that we test against our regular expression.
let regex = /hello/;
let str = 'hello world';
let result = regex.exec(str);console.log(result);
// returns [ 'hello', index: 0, input: 'hello world', groups: undefined ]
Flags:
In any regular expression, we can use the following flags:
g: matches the pattern multiple timesi: makes the regex case insensitivem: and enables multi-line mode. Where^and$match the start and end of the entire string. Without this, multi-line strings match the beginning and end of each line.u: enables support for Unicodes: short for single line, it causes the.to also match new line characters
Flags may also be combined in a single regular expression & the flag order doesn’t matter. They are added at the end of the string in regex literals:
/hello/ig.test('HEllo')Get Revive Coding’s stories in your inbox
Join Medium for free to get updates from this writer.
// returns true
If using RegExp object constructors, they’re added as the second parameter:
new RegExp('hello', 'ig').test('HEllo')
// returns trueMeta-characters
Meta-characters are characters with a special meaning. Let’s take a look at some of these here:
\d: matches any digit, being[0-9]\D: matches any character that is not a digit, effectively[^0-9]\w: matches any alphanumeric character (plus underscore), equivalent to[A-Za-z_0-9]\W: matches any non-alphanumeric character, so anything except[^A-Za-z_0-9]\s: matches any whitespace character: spaces, tabs, newlines and Unicode spaces\S: matches any character that is not a whitespace\0: matches null\n: matches a newline character\t: matches a tab character\uXXXX: matches a unicode character with code XXXX (requires theuflag).: matches any character that is not a newline char (e.g.\n) (unless you use thesflag, explained later on)[^]: matches any character, including newline characters. It’s very useful on multi-line strings
reference: https://www.easeout.co/blog/2022-01-03-understanding-regex/





