-1

I want to replace the numbers in a block of text with their halved values, but only if the number is followed by certain words. For example:

14 apples and 18 bananas cost 6 dollars.

to

7 apples and 9 bananas cost 6 dollars.

here halving only the numbers followed by fruit names. I don’t think this is doable with a simple replace, and I can’t figure out how to do it with a replace callback.

Frungi
  • 506
  • 5
  • 16

1 Answers1

-1

You can match all digits followed by a word and divide the digit by two only when the word is in a particular Set of allowed fruits.

let str = '14 apples and 18 bananas cost 6 dollars.';
const allowedFruits = new Set(['apples', 'bananas']);
let res = str.replace(/\d+ \w+/g, m => {
  const [num, word] = m.split(' ');
  if(allowedFruits.has(word)) return num/2 + ' ' + word;
  return m;
});
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80