Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple consecutive integers in a string

I have some javascript code that makes a variable with both characters and integers.

I need the consecutive integers inside this string to add together, while not affecting other individual or subsequent consecutive integers.

Lets say my input is

GhT111r1y11rt

I'd need my output to be:

GhT3r1y2rt

How would I go about doing this?

like image 296
David Avatar asked Mar 09 '23 23:03

David


1 Answers

Use String#replace method with a callback and inside callback calculate the sum using String#split and Array#reduce method.

console.log(
  'GhT111r1y11rt'.replace(/\d{2,}/g, function(m) { // get all digit combination, contains more than one digit
    return m.split('').reduce(function(sum, v) { // split into individual digit
      return sum + Number(v) // parse and add to sum
    }, 0) // set initial value as 0 (sum)
  })
)

Where \d{2,} matches 2 or more repetition of digits which is more better the \d+ since we don't want to replace single digit.

like image 185
Pranav C Balan Avatar answered Mar 19 '23 07:03

Pranav C Balan