Ben Aston Ben Aston - 10 months ago 38
Javascript Question

Using string.prototype.replace with a regexp and a function

The following returns 'entiy'. I want it to return 'entity'. How can I achieve this?

'entities '.replace(/\w(ies)(?:[\W|$|_])+/g, 'y');

Answer Source

Just capture the character before the "ies":

'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, '$1y');

Now your question asked about using a function; you can do that too:

'entities '.replace(/\w(ies)(?:[\W|$|_])+/g, function(_, before, repl) {
  return before + "y";

I don't know what you want to do with the subsequent stuff after "ies"; you can either capture it and glue it back into the replacement, or else use positive look-ahead. Portions of the input text matched by look-ahead are not part of the match involved with the replacement operation. In other words, the look-ahead does succeed or fail based on the pattern, but the characters matched are not made part of the "to be replaced" grouping.