Introduction
The programmer or developer learning web development must have encountered javascript once in his learning or working phase. Javascript is a crucial language to know to make their project responsive earlier, which was containing only CSS and HTML.
There is n number of functions and properties available in javascript, but some of them are most necessary as they make the developer's work relatively easy. One of the functions is regex. With the help of this, we can perform many operations with and on the regular expression.
We will learn all about regex in javascript while moving further with the blog, so let's get on with our topic without wasting any time further.
Regular Expressions in JavaScript
Regular expressions are strings that describe patterns, such as email addresses and phone numbers.
Regular expressions are objects in Javascript. The built-in RegExp type in JavaScript enables you to deal efficiently with regular expressions.
Regular expressions may be used to find and replace strings that match a specific pattern. They may be used in a variety of ways.
Regular expressions, for example, may be used to extract meaningful information from web scraping, such as product pricing. Regular expressions may also be used to verify form fields such as email addresses and phone numbers.
Creating a Regular Expression
In JavaScript, we generate a regular expression by enclosing its pattern in forward-slash characters (/), as seen here:
let re = /hi/;
Or you can also use the inbuilt constructor like this:
let re = new RegExp('hi');
Both these expressions match the string ‘hi’.
Testing for Matching
Many helpful methods are available in the RegExp object. One of them is the test() function, which let us see whether a string matches the regular expression pattern.
If the string argument has a match, the test() function returns true.
The test() function is used in the following example to see whether the string 'hi John' fits the pattern hi:
let re = /hi/;
let result = re.test('hi John');
console.log(result); // true
Using Pattern Flags
A RegExp object allows an extra flag argument in addition to a pattern. Flags are options that alter the way the search engine works. There are a lot of flags in regular expressions.
1) The Ignore Flag
When searching, the i flag excludes cases. Ignore is represented by the letter i.
Searches are case-sensitive by default. For instance, /hi/ matches just the string hi, not Hi. The i flag is used to search for the string hi in any case:
let re = /hi/i;
let result = re.test('Hi John');
console.log(result); // true
In this case, the /hi/i will match any string that begins with the letters hi, Hi, or HI. It's worth noting that the flag i is placed after the final forward-slash character (/).
How to utilise the flag in the RegExp function Object() is shown in the following example:
let re = new RegExp('hi','i');
let result = re.test('HI John');
console.log(result); // true
2) The Global Flag
The Global flag is another widely used flag (g). The RegExp object only looks for a match in a string and returns the first match if the global flag is not set.
When the g option is set, the RegExp searches for all possible matches and returns them all.
Flags may be combined. For example, gi flags combine the ignore (i) and global (g) flags.
The RegExp's exec() function searches a text for a match and returns an array with extensive information about the match.
If no match is found, the exec() function returns null. However, it only returns one match at a time. You'll need to run exec() many times to obtain all matches.
To return all matches, the following example uses the exec() function in conjunction with a do-while loop:
let message = 'Hi, are you there? hi, HI...';
let re = /hi/gi;
let matches = [];
let match;
do {
match = re.exec(message);
if(match) {
matches.push(match);
}
} while(match != null)
console.dir(matches);
Output:
You can compile with the help of Online Javascript Compiler for better understanding.
Searching Strings
The str.match(regexp) function retrieves all regexp matches in the string str.
The global flag is used to locate all matches (g). You may also use the ignore flag to locate matches regardless of case (i).
The match() function is shown in the following example:
let str = "Are you Ok? Yes, I'm OK";
let result = str.match(/OK/gi);
console.log(result);
Output:
Replacing String
In the example below, we will replace all the string 'OK' occurrences in the string str by using the replace() function.
let str = "Are you OK? Yes, I'm OK.";
let result = str.replace('Ok','fine');
console.log(result);
Output:
To replace all the occurrences of 'OK,' we will use the global flag g in our expression.
let str = "Are you OK? Yes, I'm OK.";
let result = str.replace(/OK/g,'fine');
console.log(result);
Output:
You can use both global and ignore flags to replace all the occurrences of the 'OK' with fine no matter the case, like shown in the below example:
let str = "Are you OK? Yes, I'm OK.";
let result = str.replace(/OK/gi,'fine');
console.log(result);
Output: