Basic Regular Expression(Regex) understanding

It is constructed either with the RegExp constructor or can be written as a literal value by enclosing a pattern in forward slash(/) characters.

let r1 = new RegExp('xyz');
let r2 = /xyz/;

The above shown syntax have the same meaning.

Testing for matches

Regular expressions have a number of methods. The simplest one is test. If you pass it a string, it will return a Boolean value(true/false).

console.log(/xyz/.test('abcxyz')); 
/true/
console.log(/xyz/.test('abxde'))
// fasle
console.log(/[0123456789]/.test(1992));
// true
console.log(/[0-9]/.test("in 1992"));
// → true

Groups

\d Any digit character
\w An alphanumeric character (“word character”)
\s Any whitespace character (space, tab, newline, and similar)
\D A character that is not a digit
\W A nonalphanumeric character
\S A nonwhitespace character
. Any character except for newline

Repeating parts of a pattern

+ -> more than once
* -> 0 or more
? -> 0 or 1 time only( question mark makes a part of a pattern optional, meaning it may occur zero times or one time)

console.log(/'\d+'/.test("'123'"));
// → true
console.log(/'\d+'/.test("''"));
// → false
console.log(/'\d*'/.test("'123'"));
// → true
console.log(/'\d*'/.test("''"));
// true

let neighbor = /neighbou?r/;
console.log(neighbor.test("neighbour"));
// → true
console.log(neighbor.test("neighbor"));
// → true

To indicate that a pattern should occur a precise number of times, use braces.
Putting {3} after an element, for example, requires it to occur exactly three
times. It is also possible to specify a range this way: {2,4} means the element
must occur at least twice and at most four times.
Here is a version of the date and time pattern that allows both single and double-digit days, months, and hours.

let dateTime = /\d{1,2}-\d{1,2}-\d{4} \d{1,2}:\d{2}/;
console.log(dateTime.test("1-30-2003 8:45"));
// → true

You can also specify open-ended ranges when using braces by omitting the
number after the comma. So, {5,} means five or more times

Grouping subexpressions

To use an operator like * or + on more than one element at a time, you have to
use parentheses. A part of a regular expression that is enclosed in parentheses
counts as a single element as far as the operators following it are concerned.
let cartoonCrying = /boo+(hoo+)+/i;
console.log(cartoonCrying.test(“Boohoooohoohooo”));
// → true

I hope you find it helpful. Please feel free to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *