Add multiple consecutive integers to a string

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

I need consecutive integers inside this line to be added together without affecting other single or subsequent integers.

Let's say my input

GhT111r1y11rt

I need my conclusion:

GhT3r1y2rt

How should I do it?

+4
source share
3 answers

Use String#replacethe callback method and internal callback to calculate the sum using String#splitand Array#reduce.

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)
  })
)
Run code

Where \d{2,}corresponds to 2 or more repetitions of digits, which is better \d+, since we do not want to replace one digit.

+7

isNaN() true, , substr

0

You can do this like this for the same number repeated several times (as in the example line):

'GhT111r1y11rt'.replace(/(\d)\1+/g, function (m,g1) { return g1 * m.length;});

(\d)fix the first digit
\1+repeat the captured digit (from group 1)

0
source

Source: https://habr.com/ru/post/1668938/


All Articles