📘str.replace()

JSvalueprimitiveStringmethod ⟩ .replace()

// quoting style: single (') -> double (")
let text = "'I'm the cook,' he said, 'it's my job.'";
text.replace(/(^|\W)'|'(\W|$)/g, '$1"$2'));
//            ╰─1──╯   ╰─2──╯ 
//  ⭐️ Groups that are not matched will be replaced by nothing.
// → "I'm the cook," he said, "it's my job."

👉 RegExpreplace pattern

// ⭐️ replacement string
//                              replacement string ↴
//          ╭1─╮ ╭─2─╮           ╭ 1 ╮  ╭ 2 ╮   ╭──────╮
let str1 = 'John Smith'.replace(/(\w+)\s(\w+)/, '$2, $1');
//          ╰ match ─╯          ╭─2─╮  ╭1─╮
log(str1);                  // "Smith, John"

// 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"

Last updated