Using regular expressions

JavaScript:
Using regular expressions

How to:

Basic Matching

To start, you can create a simple regex pattern and use it to find matches in a string. Here, we’ll find the word “code”:

const str = "I love to code in JavaScript.";
const pattern = /code/;
const result = pattern.test(str);
console.log(result); // true

Using String.prototype.match()

To retrieve an array of matches:

const matches = str.match(/code/);
console.log(matches[0]); // "code"
console.log(matches.index); // 10

Global Search

To find all the matches, use the g flag:

const globalMatches = str.match(/o/g);
console.log(globalMatches); // ["o", "o", "o"]

Case-insensitive Matching

The i flag ignores case:

const caseInsensitiveMatch = "JavaScript is fun".match(/javascript/i);
console.log(caseInsensitiveMatch[0]); // "JavaScript"

Replacing Text

Use String.prototype.replace() to replace parts of the string:

const newStr = "JavaScript is fun".replace(/fun/, "awesome");
console.log(newStr); // "JavaScript is awesome"

Using Groups

Groups can capture parts of the pattern:

const groupedPattern = /(\w+) is (\w+)/;
const replaceWithGroups = "JavaScript is fun".replace(groupedPattern, "$2 is $1");
console.log(replaceWithGroups); // "fun is JavaScript"

Third-Party Libraries

Although JavaScript’s built-in regex capabilities are powerful, some tasks might be simplified with libraries like XRegExp. It offers additional syntax and flags, making complex patterns more readable:

// XRegExp library example
const XRegExp = require('xregexp');
const str = "Cats are fantastic.";
const unicodeWordMatch = XRegExp.match(str, XRegExp('\\p{L}+'), 'all');
console.log(unicodeWordMatch); // ["Cats", "are", "fantastic"]

This snippet demonstrates using XRegExp to match all Unicode words in a string, showcasing the library’s ability to handle extended character sets beyond JavaScript’s built-in capabilities.