David David - 4 years ago 86
HTML Question

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


I'd need my output to be:


How would I go about doing this?

Answer Source

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

  '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.
