๐Ÿ“˜str.replace()

JS โŸฉ value โŸฉ primitive โŸฉ String โŸฉ method โŸฉ .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."

๐Ÿ‘‰ RegExp โŸฉ replace 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