Posted 25 Mar 2022 | by anythingultimate
JavaScript Regular Expression Part 3

 



Previous article 

Regular Expression Object Methods

MethodsDescription
exec()Executes a search for a match in a specified string. Returns the first match (array, or null).
test()Tests for a match in its string parameter. Returns true or false.
toString()Returns a string representation of a regular expression.

exec() behave differently with modifier:

Example: Search for s followed by a whitespace with global and case-insensitive modifier

let txt = "Lets start with as many HelloS as possible"
let regex1 = /s\s/gi;
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
output:
    ["s ", index: 3, input: "Lets start with as many HelloS as possible", groups: undefined]
    ["s ", index: 17, input: "Lets start with as many HelloS as possible", groups: undefined]
    ["S ", index: 29, input: "Lets start with as many HelloS as possible", groups: undefined]
    ["s ", index: 32, input: "Lets start with as many HelloS as possible", groups: undefined]
    null

Example: Search for s followed by a whitespace with global and multiline modifier

let txt = "Lets start with as many HelloS as possible"
let regex1 = /s\s/gm;
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
console.log(regex1.exec(txt));
output:
    ['s ', index: 3, input: 'Lets start with as many HelloS as possible', groups: undefined]
    ['s ', index: 17, input: 'Lets start with as many HelloS as possible', groups: undefined]
    ['s ', index: 32, input: 'Lets start with as many HelloS as possible', groups: undefined]
    null
    ['s ', index: 3, input: 'Lets start with as many HelloS as possible', groups: undefined]
let txt = "Regex is amazing"
let pattern = /amaz/g;
console.log(pattern.test(txt))

output: true
let txt = "Regex is amazing"
let pattern = new RegExp('amaz', 'g');
console.log(pattern.toString(txt))

output: /amaz/g

String methods

match()

it retrieves the result of matching a string against a regular expression.

let txt = "Get busy living or get busy dying."
let regex1 = /busy/g
console.log(txt.match(regex1));

output: (2) ['busy', 'busy']

it executes a search for a match between a regular expression and this String object. Returns the index of the first match between the regular expression and the given string, or -1 if no match was found.

let txt = "Get busy living or get busy dying."
let regex1 = /busy/g
console.log(txt.search(regex1));

output: 4

replace()

It returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If the pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

let txt = "Get bsy living or get bsy dying."
console.log(txt.replace("bsy", "busy"));

output: Get busy living or get bsy dying.
let txt = "Get bsy living or get bsy dying."
let regex1 = /bsy/g
console.log(txt.replace(regex1, "busy"));

output: Get busy living or get busy dying.

split()

Basically used to turn a string into an array.It divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern. With regex, it's become an eliminator.

let txt = "Lets start with a Hello"
let words = txt.split(' ')
console.log(words[2]);

output: with

let chars = txt.split('')
console.log(chars[6]);

output: t

let txtCopy = txt.split()
console.log(txtCopy);

output: ['Lets start with a Hello']

let regex1 = / /; or let regex1 = /\s/;  **\s -> whitespace
console.log(txt.split(regex1));

output:(5) ['Lets', 'start', 'with', 'a', 'Hello']

A whitespace character can be:

  • A space character
  • A tab character
  • A carriage return character
  • A new line character
  • A vertical tab character
  • A form feed character

Syntax

new RegExp("\\s")

or simply:

/\s/

Character repetition

Description
+Matches one or more occurrences.
?Matches zero or one occurrence.
*Matches zero or more occurrences.

Representing a group of characters

We can do this by using square brackets.

[abcd] --> it matches either a or b or c or d only once at a time.

metacharacters do not acts as metacharacters inside square bracket

for example [ .] will match either space or dot

specifying a range

[1-4] → 1 or 2 or 3 or 4

here hyphen is acting like metacharacter //exception

To exclude a character set --> use ^

metacharacters you may need to escape using backslash:
- , ^ , \ , ]

Characters set shorthands:

metacharactersshorthandDescription
[0-9]\dFind a digit
[^0-9]\DFind a non-digit character
[a-zA-Z0-9_]\wFind a word character
[^a-zA-Z0-9_]\WFind a non-word character
[\t\r\n]\sFind a whitespace character
[^\t\r\n]\SFind a non-whitespace character

Practice 1

Exercise: Using the provided array, create a second array that only includes the numbers with the 801 area code. (The area code is the first 3 numbers.)

let phoneNumbers = ["801-766-9754", "801-545-5454", "435-666-1212", "801-796-8010", "435-555-9801", 
"801-009-0909", "435-222-8013", "801-777-6655", "777-801-6788"];

let regEx = /^801-/;
let newArr = []

phoneNumbers.forEach(function (num) {
    console.log(num);
    if(regEx.test(num)){
        newArr.push(num);
    }
    console.log(regEx.test(num))

})

console.log(newArr)

output:(5) ['801-766-9754', '801-545-5454', '801-796-8010', '801-009-0909', '801-777-6655']

Practice 2

Exercise: Using the provided array, create a second array that only includes the numbers with the 801 area code. (The area code is the first 3 numbers.) Make sure that the phone numbers are valid (nnn-nnn-nnnn).

const phoneNumbers = ["801-766-9754", "801-545-5454", "435-666-1212", "801-796-8010", 
"435-555-9801", "801-009-0909", "435-222-8013", "801-777-66553", "801-777-665-", 
"801-77A-6655", "801-778-665"];

const regEx = /^801-\d\d\d-\d\d\d\d$/;

const newArray = phoneNumbers.filter(elem => regEx.test(elem));

console.log(newArray);

output:(4) ['801-766-9754', '801-545-5454', '801-796-8010', '801-009-0909']

------------------------- Click here to continue -------------------------

Liked This Page. Spare a while to share it.

About The Admin Of This Blog:

Author Of This Article

I am a passionate and experienced Full Stack Web Developer having 4+ years of experience in Web Development using Laravel, React, WordPress, Angular, Vue, Bootstrap, Tailwind CSS, Saas, ES6, etc. I like to explore and learn about new technologies whenever I get any chance.

Stay Connected With Me On GooglePlus, Facebook And Twitter

Calculator

C
±
x ²
%
7
8
9
*
(
4
5
6
/
)
1
2
3
-
+
0
.
=
x ²
x^
sin
cos
tan
x !
π
C
log
ln
e
rad
7
8
9
*
(
4
5
6
/
)
1
2
3
-
+
0
.
%
±
=

Calender

Sa
Su
Mo
Tu
We
Th
Fr

Popular Posts

Total Blog Views