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. get index of first match
// find index of first digit occurrence console.log( "there are 36 cats".search(/\d/), ); // 10 // return the start position of match // if not found, returns -1 console.log( "no cat".search(/\d/), ); // -1
Example. find pattern
console.log( "394 cats and 98 dogs.".match(/\d+/g), ); // [ "394", "98" ]
Example. regex replace
console.log( "year 2026-09-08".replaceAll(/(\d\d\d\d)-\d\d-\d\d/g, `$1`), ); // year 2026