Register Login

Regular Expressions & Matching Strings in JavaScript

Updated Jan 27, 2023

Writing code to match strings or string patterns can be bothersome. Developers usually take the aid of Regular Expressions that define some rules. A string must follow these rules to get matched. Here, we'll discuss Regular Expression and some methods generally used for matching strings in JavaScript.

What is a Regular Expression?

Regular Expressions ( RegEx for short) are the expressions of patterns that can be utilized for text searching and validating, splitting strings, and much more. These patterns consist of characters, digits, and other special characters.

Developers arrange a regular expression in such a form that it can match some segments or parts of the string.

Here is an example of a Regular Expression:

/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/ (This expression validates an email address)

How to write a Regular Expression?

There are two ways to construct a Regular Expression:

  1. Create regular expressions using regular literal expressions. It consists of a pattern of characters between two slashes. Example: const re = /ab+c/;
  2. Creating regular expressions using the RegExp() constructor. Example: const re = new RegExp('ab+c');

Regular Expression patterns

A regular expression pattern may have simple characters, such as /abc/, or a mixture of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/

Modifiers

Modifiers get employed while performing global and case-sensitive searches. Below are the modifiers with their description:

g: This modifier comes in use while performing a global search.
i: This modifier is for performing case-insensitive matches
m: It enables to perform multiline matching

Brackets

Brackets define the range of characters.

  1. The expression to pick/find out any character between the brackets is [abc], and to find a character that's not between brackets: [^abc]. 
  2. To find any number/digit between brackets, the expression used is [0-9], and [^0-9]  o find any non-digit that is not between brackets.
  3. The expression to find any of the alternatives described is (x|y).

Metacharacters

Metacharacters are characters that have a special meaning. Some of them are:

. : To find a single character, except newline or line terminator
\w: To find a word character
\W: To find a non-word character
\d: To find a digit
\D: To find a non-digit character
\s: To check if there is a whitespace character
\S: To check if there is a non-whitespace character
\0: To find a NULL character

Quantifiers

n+: This quantifier match any string that contains at least one n
n*: This quantifier checks if there is a string that has zero or more occurrences of n
n{X}: This quantifier inspects if there is a series of X n's in the string
n{X,Y}: This quantifier checks if any string has a series of X to Y n's

RegExp object methods

compile(): To compile a regular expression
exec(): To test if there is a match in a string and returns the first match
test(): Returns true if there is a match or else false
toString(): Converts a regular expression to its string value

String matching in JavaScript

Below are some inbuilt functions in JavaScript to perform the string-matching tasks:

match()

The match() gets employed for matching a string against a regular expression. If the string gets matched, it returns it. If there is no match, it returns null.

Code:

<html>
<head>
<title>Regular Expressions and Matching Strings in JavaScript</title>
</head>

<body>
	<p>Search for "<span id="jdr"></span>":</p>
	<script>
	let text = "Good writers accomplish tasks by immediately establishing each paragraph’s topic";
	let result = text.match(/immediately establishing each paragraph’s topic/); 
	document.getElementById("jdr").innerHTML = result;
	</script>
</body>
</html>

Output:

Run Code Snippet

search()

The search() gets employed for matching a string against a regular expression. It returns the index number of the first match, and if there is no match, it returns -1. It is case-sensitive.

Code:

<html>
<head>
<title>Regular Expressions and Matching Strings in JavaScript</title>
</head>

<body>
	<p>String "Blue" is at position: <span id="jdr"></span></p>
	<script>
	let text = "Mr. Blue has a blue house."
	let pos = text.search(/Blue/);
	document.getElementById("jdr").innerHTML = pos;
	</script>
</body>
</html>

Output:

Run Code Snippet

replace()

The replace() method analyzes a string for a value or a regular expression. It returns a new string with the value swapped. It does not alter the original string.

Code:

<html>
<head>
<title>Regular Expressions and Matching Strings in JavaScript</title>
</head>

<body>
	<p><strong>Orignal</strong>: Mr. Gosh has a blue villa and a blue porche.</p>
	<p id="demo"><strong>After Replace</strong>: Mr. Gosh has a blue villa and a blue porche.</p>
	<script>
	let st = document.getElementById("demo").innerHTML; 
	let re = st.replace(/blue/g, "red");
	document.getElementById("demo").innerHTML = re;
	</script>
</body>
</html>

Output:

Run Code Snippet

Conclusion:

Developers Regular Expressions to define some rules that a string must follow to get matched. They are the patterns that can be utilized for text searching and validating, splitting strings, and much more.

They may consist of characters, digits, and other special characters. When it comes to matching strings, there are three common functions/methods in JavaScript. These are:

  1. match()
  2. replace()
  3. search()


×