🔰replacer function

JSvalueprimitiveStringmethod.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