I'm trying to use RegExp
with String.replace
to replace the second to last occurrence of a word in a space-separated string.
I don't understand why my code isn't working. I have parentheses around the correct match, so why is it replacing the match of the entire RegExp
instead of just what's inside the capture group?
const re = /(\w+) \w+$/;
const string = 'john deer senior third';
const result = string.replace(re, match => `[${match}]`);
console.log(result); // john deer [senior third]
Desired result:
john deer [senior] third
See the MDN for the signature of a replacer function in String.prototype.replace
. The first argument is the full match, the capture groups come afterwards.
Also, replace
will replace the full match, not only the first capture group (there can also be more than one capture group in a regex). To mitigate this, you could use a lookahead, or concatenate the latter half back in:
let a = 'john deer senior third'.replace(/\w+(?= \w+$)/, m => `[${m}]`);
let b = 'john deer senior third'.replace(/(\w+)( \w+)$/, (_, a, b) => `[${a}]${b}`);
console.log(a);
console.log(b);
There may be even more elegant ways to do this aswell.