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 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”.
console.log("something in tthe water".search(/tt+/)); // 13 /* return the start position of match if not found, returns -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" ]
JavaScript. Regular Expression
- JS: Regular Expression Tutorial
- JS: Regular Expression Functions
- JS: Create Regex Object
- JS: Regular Expression Syntax
- JS: Regular Expression Flags
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp (class)
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec