๐Ÿ”ฐreplacer function

JS โŸฉ value โŸฉ primitive โŸฉ String โŸฉ method โŸฉ .replace() โŸฉ replacer function

// p1: nondigits 
// p2: digits 
// p3: non-alphanumerics
let regex = /([^\d]+)(\d+)([^\w]+)/;
// groups:   โ•ฐโ”€ p1 โ”€โ•ฏโ•ฐp2โ”€โ•ฏโ•ฐโ”€ p3 โ”€โ•ฏ

//     offset โ†ด
//         012345678901234567
let str = '000abc12345#$*%xxx';
//         โ•ฐโ”€โ•ฏโ•ฐ1โ•ฏโ•ฐโ”€2โ”€โ•ฏโ•ฐ3โ”€โ•ฏโ•ฐโ”€โ•ฏ
//          $`โ•ฐโ”€ match โ”€โ”€โ•ฏ $'

// โญ๏ธ replacement: (replacer function)
let str2 = str.replace(regex, (
  match,            // matched substring = $&
  p1, p2, p3,       // capture groups = $1, $2, $3 ...
  offset,           // offset (index) of matched substring
  string,           // whole string
  groups            // "named" capturing groups (object)
) => {
  //                     3 โ†ด      undefined โ†ด
  log(match, p1, p2, p3, offset, string, groups);
  return '--' + ([p1, p2, p3].join('-')) + '--';
});

// str.replace()                            โ•ญโ”€โ”€โ”€ replaced โ”€โ”€โ”€โ•ฎ
log(str2);                           // "000--abc-12345-#$*%--xxx"
// โญ๏ธ ๆณจๆ„๏ผšไธๅปๅˆ็š„้ƒจๅˆ†ๆœƒๅŽŸๅฐไธๅ‹•็•™ไธ‹ไพ†๏ผš     โ•ฐโญ๏ธโ•ฏ                 โ•ฐโญ๏ธโ•ฏ

// camel case to kebab case
let kebab = 'borderTop'.replace(/[A-Z]/g, (match, offset) => 
    (offset > 0 ? '-' : '') + match.toLowerCase()
);

log(kebab);           // "border-top"

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

// replace function
"the cia and fbi".replace(/\b(fbi|cia)\b/g, 
    match => match.toUpperCase()    // โ†’ the CIA and FBI
)

Last updated