🔰replace pattern
JS ⟩ value ⟩ object ⟩ regex ⟩ pattern ⟩ replace pattern
$n // Insert the contents of unnamed capture #n
${foo} // Insert the contents of named capture “foo”
$0 // Insert all text matched in the regex (automatic unnamed capture)
$` // (backtick) Insert text before $0
$' // (single-quote) Insert text after $0
$_ // Insert the entire original filename (same as $`$0$')
$# // Insert a number sequence (see Numbering)
$$ // Insert an actual $ character (therefore, $$# to insert actual $#)
// For unnamed captures, use ${n} if the following character is an actual digit
// Any text other than the variables above will be replaced as-is.
👉 str.replace() ⟩ replacer function for more examples.
// global vs non-global replace
"Borobudur".replace(/[ou]/ , "a") // Barobudur
"Borobudur".replace(/[ou]/g, "a") // Barabadar
// replace pattern
const names = "Liskov, Barbara\nMcCarthy, John\nWadler, Philip"
names.replace(/(\w+), (\w+)/g, "$2 $1") // unnamed capture $n
// Barbara Liskov
// John McCarthy
// Philip Wadler
// 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."
Last updated