JS: Regular Expression Tutorial
What is Regular Expression
Regular Expression (or regex in short) is a character sequence that represent a pattern of text. For example, you can use it to find all numbers in a file.
Regex is used by many functions to check if a string contains certain pattern, or extract it, or replace it with other text.
Regex Pattern and Flags
Regular Expression has 2 parts:
- regex → specify a text pattern.
- flags → flags is used to tweak regex syntax meaning or how the regex function behaves. e.g. ignore letter case.
Create Regex Object
Example. Find Index of Match
Check if a string contains repeated “t”.
// find 2 or more t console.log("something in tthe water".search(/tt+/)); // 13 // return the start position of match // if not found, returns -1 console.log("something".search(/tt+/)); // -1
Example. Regex Replace
console.log(`i have 1 cat, he has 2 cats.`.replaceAll(/(\d+) cat/g, `$1 dog`)); // i have 1 dog, he has 2 dogs.
Example. Capture Numbers
console.log("there are 394 cats and 98 dogs.".match(/\d+/g)); // [ "394", "98" ]