Sitemap
Revive Coding

Revive Coding

Revive Coding is a place where you learn Web Development. Here we teach you, art of becoming Full Stack Web Developer and ready for your Dream Job.

Regular Expression Flag | JavaScript Tutorial

2 min readAug 13, 2022

--

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 times
  • i: makes the regex case insensitive
  • m: 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 Unicode
  • s: 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:

Get Revive Coding’s stories in your inbox

Join Medium for free to get updates from this writer.

/hello/ig.test('HEllo')
// returns true

If using RegExp object constructors, they’re added as the second parameter:

new RegExp('hello', 'ig').test('HEllo') 
// returns true

Meta-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 the u flag)
  • .: matches any character that is not a newline char (e.g. \n) (unless you use the s flag, 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/

--

--

Revive Coding
Revive Coding

Written by Revive Coding

Revive Coding is a place where you learn Web Development. Here we teach you, art of becoming Full Stack Web Developer and ready for your Dream Job.