Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript split string by regex

I will have a string never long than 8 characters in length, e.g.:

// represented as array to demonstrate multiple examples
var strs = [
    '11111111',
    '1RBN4',
    '12B5'
]    

When ran through a function, I would like all digit characters to be summed to return a final string:

var strsAfterFunction = [
    '8',
    '1RBN4',
    '3B5'
]

Where you can see all of the 8 single 1 characters in the first string end up as a single 8 character string, the second string remains unchanged as at no point are there adjacent digit characters and the third string changes as the 1 and 2 characters become a 3 and the rest of the string is unchanged.

I believe the best way to do this, in pseudo-code, would be:

1. split the array by regex to find multiple digit characters that are adjacent
2. if an item in the split array contains digits, add them together
3. join the split array items

What would be the .split regex to split by multiple adajcent digit characters, e.g.:

var str = '12RB1N1'
  => ['12', 'R', 'B', '1', 'N', '1']

EDIT:

question: What about the string "999" should the result be "27", or "9"

If it was clear, always SUM the digits, 999 => 27, 234 => 9

like image 344
Harry Avatar asked Jun 11 '13 19:06

Harry


2 Answers

You can do this for the whole transformation :

var results = strs.map(function(s){
    return s.replace(/\d+/g, function(n){
       return n.split('').reduce(function(s,i){ return +i+s }, 0)
    })
});

For your strs array, it returns ["8", "1RBN4", "3B5"].

like image 70
Denys Séguret Avatar answered Oct 01 '22 22:10

Denys Séguret


var results = string.match(/(\d+|\D+)/g);

Testing:

"aoueoe34243euouoe34432euooue34243".match(/(\d+|\D+)/g)

Returns

["aoueoe", "34243", "euouoe", "34432", "euooue", "34243"]
like image 42
mzedeler Avatar answered Oct 01 '22 23:10

mzedeler