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