Regular Expressions in Javascript

Rollin_J
3 min readMay 1, 2021

Things you need to know about regular expression in JS (Part I)

Image from unsplash

Regular expressions are patterns used to match character combinations in strings. Regular expressions are a powerful way of doing search and replace in strings.
To define regular expressions,you can place your pattern within two forward slashes or can use RegExp object as shown below

Syntax:-

define regex

Some useful regular expression methods:

1st:exec()
This returns an array of information if patterns matches given sring or null otherwise:

string str contains ‘popular’ two times but exec() method return information only for first occurance.

To get information of next occurance use flag ‘g’ (gloabl) along with the expression as shown here →

1st console gives information of pattern ‘popular’ at index 5, other gives information of pattern at index 54

few more useful flags,

syntax to use flag:
var regex = /pattern/flags;

var re = new RegExp('pattern', 'flags');

2nd test(): Returns true if pattern is present in string otherwise returns false

returns true

3rd match():Return an array containing all of the matches, or null if no match is found. Here is an example:

as we are using ‘g‘ flag, match() method return array of all matching elements as:

4th search():Returns the index of the match pattern or -1 otherwise.

consoles 14(index of pattern ‘popular’)

5th replace(): Replaces the matched substring with a replacement substring.

consoles

--

--