36.6 C
Jaipur
Wednesday, May 25, 2022

Regex in javaScript | Explained with Examples

Must read

When a developer first lays his eyes on regular expressions or regex it seems gibberish. However they may look, regular expressions are extremely useful and make you an effective programmer. The Regex concept is a little complicated, however in this post, we will walk you through simple steps along with examples to help you master Regex in JavaScript.

What is Regex in JavaScript?

Regex or Regular expression is simply a string that defines a pattern and is very useful in finding a pattern in a string or replacing a string with a matched pattern. To put it simply, suppose you want to validate an email address or phone number with a specified pattern, then Regex comes in handy.

Regex Syntax:

We enclose a pattern in forward slash “/” as shown above. We can also use the RegExp constructor to define a Regex pattern:

var myRegex = new RegExp(‘abc’);

Now that we know what regex is and what is its syntax, let us now see how to specify a pattern using Regex in JavaScript.

Specify Pattern using Regex

To specify patterns using regex we use metacharacters which are characters that hold special meaning. Metacharacters and what they represent in Regex is given in the table below:

Meta character What does it do?
[] (Square brackets) Whatever we write in the square brackets will be matched with a given string. For example [abc] matches the a, b, and c characters with a specified string. We can also specify a range for example [a-f] is the same as [abcdef] or [1-5] is the same as [12345].
^ (Caret symbol) The Caret symbol is used to check whether a specified text or string starts with a certain character or not e.g. ^a matches with abc however ^a does not match with bac. The Caret symbol within square brackets is used to take the complement of specified characters. For example [^abc] specifies that except a,b, or c any character present will be matched.
$ (Dollar symbol) The $ symbol is used wherever we want to check whether a string ends with a certain character or not. For example, a$ means that whatever string we are matching with should have a at the end, that is amnesia will be matched with a$ however heart will not.
* (Star symbol) The star symbol matches 0 or more occurrences of the specified pattern or character present left from the star symbol in a string. For example, ma*n means that search m and a character in a string. Hence mn will have 1 match. Main will have no match as a is not followed by n and there is i in between.
+ (plus symbol) The plus symbol is just like a star symbol with the exception that it matches 1 or more occurrences of the specified pattern or character. For example, when mn string is searched for the expression ma+n there is no match however when the expression is searched for man there is one match.
{} (Braces) To have a clear understanding of braces let us first see the following code i-e {2,3} which means at least 2 and at most 3 repetitions is possible of the pattern left from it. For example, the expression a{2,3} when matched with the string “abc dat” will have no match however when the expression is matched with the “abc daat” it will have one match i-e daat.
| (Alteration) The Alteration or vertical bar symbol is used for the or operator. For example, the expression a|b indicates that a or b should be present in a specified string. Hence fgh has no matches and abc has 2 matches that are ab.
(Backslash) The purpose of backslash is to escape characters as well as escape all metacharacters. In simple words, if you are unsure whether a character contains some special meaning or not then place a backslash before the character. Hence that character will not be treated in any special way, for example, $a expression will match any text or string that has a $ followed by a.

Now that we know how to specify patterns using Regex let us now go through some Regex methods to match a regex with a specified string.

Test patterns for matching

Earlier, we discussed how we can use the RegExp constructor to initialize the RegExp object with a specified pattern. This RegExp object gives us many built-in methods and one of them is the test() method. The test() method is very useful as it checks a string for a specified pattern in the regular expression. The test() method returns a boolean value, that is if the specified pattern matches the string then true is returned, otherwise false is returned. To better understand the test() method let’s see an example:

var myRegex = /Hello/;

var output = myRegex.test(‘Hello World!’);

console.log(output); // true

In the above code first, we defined a pattern that is Hello and then used the built-in method test() on the specified pattern to check whether the string Hello World! contains Hello or not. The result is given below:

Instead of the boolean value, the string match can also be returned with another built-in method which is the match() method. The code below is implementing the match() method:

var myString = “Hello World!”;

// pattern

var myRegex = /Hello/;

console.log(myString.match(myRegex)); // Hello

An array will be returned which will contain the input string to the match() method, the index on which the match is found as well as the match itself.

If a match is not found then null will be returned:

var myString = “Hello World!”;

// pattern

var myRegex = /Hi/;

console.log(myString.match(myRegex)); // null

Pattern Flags

We saw that the RegExp object accepts a pattern; however it should also be noted that the RegExp can also take an optional flag parameter. Flags are just a little extra topping that changes the searching behavior.

The first flag we will discuss is the ignore flag denoted by i. By default, pattern searching in Regex is case sensitive so to ignore cases we use the ignore flag (i) when searching for a pattern. For example:

var myRegex = /hello/i;

console.log(myRegex.test(“Hello World!”)); // true

Although the pattern has hello and the string in the test method has the first letter capital, it’s still a match because we used the ignore flag (i) hence the result will be true:

To use the ignore flag with RegExp object copy the following code:

var myRegex = new RegExp(‘hello’, ‘i’);

console.log(myRegex.test(“Hello World!”)); // true

Similarly, we can use the global flag denoted by g whose function is to return all the matches in the string. Without the global flag, only the first match is returned. The below code uses the global flag:

var myString = ‘Hello World! and hello Universe!’;

var myRegex = /hello/gi;

var matches = [];

var match;

do {

match = myRegex.exec(myString);

if(match) {

matches.push(match);

}

} while(match != null)

console.log(matches);

First, we initialized myString which contains the string that will be used for searching a pattern, and after that, we created a regular expression pattern that contains the global flag and ignore flag. The global flag will search for all the matches whereas the ignore flag will ignore case sensitivity. In the above code, another built-in method is used which is the exec() whose function is to return an array that contains the match. However, if there was no match between the pattern and the string then null will be returned. It should be noted that the exec() method only returns a single match at one time hence we use the do-while loop and push all the matches to the matches array. In the end, we console log the matches array which contains all the matches:

Conclusion

Regex is a string that defines a pattern or finds a pattern in a specified string. We use the RegExp object or the forward-slash / to define Regex. The RegExp also takes an optional parameter i-e flag which changes the searching behavior. To specify patterns we use metacharacters which are some specific characters having special meanings. To test whether it matches with a string or not we use built-in methods like test(), match(), or exec().

In this post, first, we defined what is Regex in JavaScript and what is Regex syntax in JavaScript. Then we showed you how to specify patterns using Regex and test patterns in JavaScript. In the end, we discussed the two flags that are global and ignore flags.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -

Latest article