๐Ÿ“˜str.match()

str.match() ็š„ๅ›žๅ‚ณๅ€ผๆœ‰ไธ‰็จฎๆจกๅผ๏ผš

-----------------------------------------------
   matched   /g    return value    capture groups
-----------------------------------------------
1. โœ… 	     โœ…     all matches	   โŒ
2. โœ…        โŒ     first match     โœ…
3. โŒ               null
-----------------------------------------------
  1. global mode (with /g set): return array of all matches (without info about capturing groups)

  2. non-global mode (with /g not set): return array of first match (including additional info about capturing groups)

  3. no match: return null.

//                       first match โ†ด
//             0         1         2         3         4
//      index: 01234567890123456789012345678901234567890
//                                   โ•ญโ”€โ”€ first match โ”€โ”€โ•ฎ
const found = 'For more information, see Chapter 3.4.5.1'.match(
//                                       โ•ฐโ”€โ”€โ”€ group โ”€โ”€โ”€โ•ฏ
    /see (chapter \d+(\.\d)*)/i     // ignore case, non-global
);

// โญ๏ธ three modes of str.match(regex) method's return value

log(found);
// โญ๏ธ 2. non-gloabl mode:
//   (return array of informations about first match)
// [
//   'see Chapter 3.4.5.1',         // whole match
//   'Chapter 3.4.5.1',             // first capture group โญ๏ธ
//   '.1',                          // last value captured by '(\.\d)'
//   index: 22,                     // index of the whole match
//   input: 'For more information, see Chapter 3.4.5.1',    // original string
//   groups: undefined              // object of named capturing groups
// ]

let str = "We will, we will rock you";

// โญ๏ธ 1. global mode:
//   (return array of all matches, no capturing groups)
str.match(/we/gi),      // [ 'We', 'we' ]

// โญ๏ธ 3. no match:
//    (return null)
str.match(/they/),      // null โญ๏ธ

Last updated