JS: String.prototype.match
💡 TIP:
use
String.prototype.match
only if you want first occurrence or first captured group.
Else, use
String.prototype.matchAll instead, because it's much simpler, and gets all occurrence and captured groups (if any).
str.match(findStr)
-
The string findStr is converted to regex first by RegExp, then
str.match(regexObj)
is called. str.match(regexObj)
-
Return a Iterable or null if no match.
If regexObj has flag
g
, the result is all occurences, else it is captured groups (and if the regex does not contain any capture, it return first occurrence).Return Value regex has global flag regex no global flag regex has capture group all occurrences captured groups regex has no capture group all occurrences 1st match (array of 1 item) In result array, index 0 is the whole matched string, index 1 is 1st captured group or occurrence, index 2 is the 2nd, etc.
The result array have these properties (their values are undefined if no g flag):
index
→ The beginning position of first occurrence.input
→ The input string.groups
→ (JS2018) A object. Key is name of named capture group. Value is corresponding substring, orundefined
if there is none.
/* get all occurrence of a match */ const xtext = ` src="cat.jpg" src="dog.jpg" src="house.jpg" `; // get all image file names const xre = /[\w]+.jpg/g; const xresult = xtext.match(xre); console.log(xresult[0] === "cat.jpg"); console.log(xresult[1] === "dog.jpg"); console.log(xresult[2] === "house.jpg"); // start of match console.log(xresult.index === undefined); // original string console.log(xresult.input === undefined); // named capture console.log(xresult.groups === undefined);
/* get all captured matches */ const xtext = `img src="cat.jpg" alt="my cat" width="600" height="400"`; /* capture attribute values in a image tag */ const xre = /src="([^"]+)" alt="([^"]+)" width="([^"]+)" height="([^"]+)"/; const xresult = xtext.match(xre); // whole matched part // note, no starting img console.log( xresult[0] === `src="cat.jpg" alt="my cat" width="600" height="400"`, ); // 1st capture console.log(xresult[1] === "cat.jpg"); // 2nd capture console.log(xresult[2] === "my cat"); // 3rd capture console.log(xresult[3] === "600"); // 4th capture console.log(xresult[4] === "400"); // start of match console.log(xresult.index === 4); // original string console.log(xresult.input === xtext); // no named capture console.log(xresult.groups === undefined);
JavaScript, Regular Expression
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp Object
- 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