Technical skill practice

Replace a String in JavaScript: First Match, All Matches and Regex

String replacement returns a new string. Choose whether you mean one literal occurrence, every literal occurrence or a pattern. The method and replacement form determine what happens; the source text does not change.

The task

Update repeated draft markers, then normalize numbered section labels with a regular expression. Also insert a literal dollar sequence through a callback so it is not interpreted as replacement syntax.

Runnable Node 22 example

const assert = require('node:assert/strict');

const label = 'draft / draft';
assert.equal(label.replace('draft', 'ready'), 'ready / draft');
assert.equal(label.replaceAll('draft', 'ready'), 'ready / ready');
assert.equal(label, 'draft / draft');
const numbered = 'part-07 part-12'.replace(/part-(\d+)/g, (_, digits) => `section-${Number(digits)}`);
assert.equal(numbered, 'section-7 section-12');
const literal = 'X'.replace('X', () => '$&');
assert.equal(literal, '$&');
assert.equal('X'.replace('X', '$&'), 'X');
console.log(numbered);

Expected output and explanation

The string search in replace changes the first draft only; replaceAll changes both. The regex uses g to visit both numbered labels and passes the captured digits to the callback. Converting those digits produces the intended unpadded section number.

The last assertions demonstrate why a replacement string and callback result are different. In a replacement string, $& refers to the matched text. Returning $& from a callback inserts those characters literally. Choose the form that matches your data instead of trying to repair the output afterward.

Output from the example

section-7 section-12

Pitfall to check

Do not interpolate arbitrary user text directly into a regex and assume it remains a literal search. Pattern metacharacters change its meaning. For straightforward repeated text, a literal replaceAll avoids that pattern-building step.

Questions, answered

Does replace edit the original variable’s string?

No. It returns a string result. Assign or use that result deliberately; merely calling replace does not update the existing string value.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.