umma.dev

Regular Expressions

What are regular expressions and when would you need to use them? Here I go into methods used for regular expressions.

What Are Regular Expressions?

Regular expressions are patterns that used to match combinations of characters in strings.

Methods used:

exec()

Search for a match in a string. Returns an array of information or null on a mismatch.

test()

Tests for a match in a string. Returns true or false.

match()

Returns an array containing all matches and null if no match is found.

matchAll()

Returns an iterator containing all of the matches, cinluding capturing groups.

replace()

Run a search for a match in a string and replace the matched substring with a replacement substring.

replaceAll()

Similar to replace() but will search for ALL matches.

split()

Uses a regexp or a fixed string to break a string into an array of substrings.

Examples

let text = "Hello World";
let n = text.search("Hello"); // 0
let text = "Hello World";
let n = text.search(/World/i); // 5
let text = "Hello World";
let result = text.replace("World", "Me");
console.log(/abc/.test("abcde")) // true
console.log(/abc/.test(abbde)) // false