JS: RegExp 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.
Basic Example
Check if a string contains repeated t
const xtext = "something in tthe water"; const result = xtext.search(/tt+/); console.log(result); // 13 // return the start position of match // if not found, returns -1
search
is a string method.- The syntax
/…/
is a literal expression for regex object. - In between the slashes, is the RegExp Syntax for a text pattern.
- The
string.search(regex)
means search the regex in string string.
Example: Regexp Replace
const xx = `i have 1 cat, and my mom has 2 cats.`; const yy = xx.replaceAll( /(\d+) cat/g, `$1 dog`, ); console.log(yy === `i have 1 dog, and my mom has 2 dogs.`);
Example: Capture Numbers
const xtext = "there are 394 cats and 98 dogs."; const regex = /\d+/gi; console.log(xtext.match(regex)); // [ "394", "98" ]
Example: Capture HTML Tag Attributes
// capture the attribute values in a HTML image tag const xtext = `<img class="i" src="cat.jpg" alt="my cat">`; const result = xtext.match(/<img class="([^"]+)" src="([^"]+)" alt="([^"]+)">/); console.log(result); /* [ '<img class="i" src="cat.jpg" alt="my cat">', "i", "cat.jpg", "my cat", index: 0, input: '<img class="i" src="cat.jpg" alt="my cat">', groups: undefined ] */
JavaScript. Regular Expression
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: Create Regex Object
- JS: RegExp Syntax
- JS: RegExp Flag
- 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