JS: String.prototype.match

By Xah Lee. Date: . Last updated: .
str.match(findStr)

The string findStr is converted to regex first by RegExp, then str.match(regex_obj) is called.

str.match(regex_obj)

Return a Iterable or null if no match.

  • If regex_obj has regex flag g, the result is all occurences.
  • Else, the result is all captured groups of first matched string. (and if the regex does not contain any capture, it return first matched string).
Return Value
has flag gno flag g
capture groupall occurrencescaptured groups in first matched string
no capture groupall occurrencesfirst matched string (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 → (new in ECMAScript 2018) A object. Key is name of named capture group. Value is corresponding substring, or undefined if there is none.

Example

Get all occurrences

/* get all occurrences of jpg file names */

const xtext = `
cat.jpg
dog.jpg
house.jpg
`;

// use flag global
const xresult = xtext.match(/[\w]+.jpg/g);

console.log(xresult);
// [ "cat.jpg", "dog.jpg", "house.jpg" ]

Get all captures of first match

/* get all captures of first match */

const xtext = `
src="hhkb_keyboard.jpg" alt="hhkb"
src="kinesis_360_keyboard.jpg" alt="kinesis_360"
src="glove_80_keyboard.jpg" alt="glove_80"
src="uhk_80_keyboard.jpg" alt="uhk_80"
`;

// no flag global
const xresult = xtext.match(/src="([^"]+)" alt="([^"]+)"/);

console.log(xresult);
/*
[
  'src="hhkb_keyboard.jpg" alt="hhkb"',
  "hhkb_keyboard.jpg",
  "hhkb",
  index: 1,
  input: "\n" +
    'src="hhkb_keyboard.jpg" alt="hhkb"\n' +
    'src="kinesis_360_keyboard.jpg" alt="kinesis_360"\n' +
    'src="glove_80_keyboard.jpg" alt="glove_80"\n' +
    'src="uhk_80_keyboard.jpg" alt="uhk_80"\n',
  groups: undefined
]
*/

Get just first match

/* get just first occurrence */

const xtext = `
src="hhkb_keyboard.jpg" alt="hhkb"
src="kinesis_360_keyboard.jpg" alt="kinesis_360"
src="glove_80_keyboard.jpg" alt="glove_80"
src="uhk_80_keyboard.jpg" alt="uhk_80"
`;

// no flag global, no capture
const xresult = xtext.match(/src="[^"]+" alt="[^"]+"/);

console.log(xresult);
/*
[
  'src="hhkb_keyboard.jpg" alt="hhkb"',
  index: 1,
  input: "\n" +
    'src="hhkb_keyboard.jpg" alt="hhkb"\n' +
    'src="kinesis_360_keyboard.jpg" alt="kinesis_360"\n' +
    'src="glove_80_keyboard.jpg" alt="glove_80"\n' +
    'src="uhk_80_keyboard.jpg" alt="uhk_80"\n',
  groups: undefined
]
*/

JavaScript. Regular Expression

JS String.prototype