How to use Regex in JavaScript — Part 1
In this article we will learn how, why and where we can use regular expressions shortened as Regex to simplify our code in JavaScript.
Regex can be used to find out if a string matches a certain specific pattern. Let us consider that we need to validate the password set by user which must have a certain set of special characters and case-sensitive letters, or we need to check the email provided is valid. There might be cases where we need to extract information from logs or URL. Using regex patterns it is easily achievable.
Creating Regex in JS
Regular expressions are objects in JavaScript. We can create regex by any of the following two ways:
let regex1 = new RegExp("Hello");
let regex2 = /Hello/;
Once we have a regex object, you can then use it with one of the methods on RegExp Constructor or the String object wrapper.
Using Regex in JS
We can use the regex pattern created to find it’s match in the given string.
let txt = "Hello world example."
let regex1 = new RegExp("Hello");
let regex2 = /worlds/;
//test returns true or false based on match found
console.log(regex1.test(txt)) //true
console.log(regex2.test(txt)) //false
//Provides additional information when match found
console.log(regex1.exec(txt)); //['Hello', index: 0, input: 'Hello world example.', groups: undefined]
console.log(regex2.exec(txt)); // null
Apart from the above methods, we have other methods as well from the String object which can be used with Regex patterns.
let txt = "Hello world example."
let regex1 = new RegExp("Hello");
let regex2 = /worlds/;
//Provides additional information when match found
console.log(txt.match(regex1)) //['Hello', index: 0, input: 'Hello world example.', groups: undefined]
//Returns the index of the match
console.log(txt.search(regex1)) //0
//Returns a new string with replaced value
console.log(txt.replace(regex1, "Hi")) //'Hi world example.'
//Returns an array based on pattern split
let regex3 = '/\s/' //pattern for matching whitespace character
console.log(txt.split(regex3)) //['Hello', 'world', 'example.']
Regular Expression Flags
Regular expressions have optional flags that allow for functionality like global searching and case-insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression.
let txt = "Olek finds apple pies tastier than banana pies at Peppa's Pie store."
//returns all possible case-sensitive matches
let regex1 = /pie/g; //the flag should be appended as /patters/flags
console.log(txt.match(regex1)) // ['pie', 'pie']
//returns all possible matches
let regex2 = /pie/gi; //multiple flags can be appended in any order
console.log(txt.match(regex2)) // ['pie', 'pie', 'Pie']
//seeing the behaviour without flags
let regex3 = /pie/
//returns first match always
console.log(txt.match(regex3)) //['pie', index: 17, input: "Olek finds apple pies tastier than banana pies at Peppa's Pie store.", groups: undefined]
console.log(regex3.exec(txt)); //['pie', index: 17, input: "Olek finds apple pies tastier than banana pies at Peppa's Pie store.", groups: undefined]
Testing Regex patterns
We can easily test our patterns using https://www.regexpal.com/ and debug.
Using Metacharacters in Regex
When the search for a match requires something more than a direct match, such as finding one or more b’s, or finding number of characters between two specific letters, we can use special characters.
The Wildcard . Metacharacter
It matches for almost any character that may come on that index. New line character is an exception.
If we include the flag ‘s’ (dotAll flag) then the new line also matches.
Escaping Metacharacters
To include the literal value of a metacharacter in a pattern there might be cases where we want to escape it. We can do that using ‘\’.
Matching control characters
Control characters such as /n, /t, /r etc… can be matched as follows.
That’s all for this article, in the next part we will learn more on working with character sets and repetitions in regex.
Thanks for reading, hope this was helpful! Stay tuned for the next part ;)