Ted Ted - 3 years ago 56
Javascript Question

Extract numeric and text parts of a string, in varying formats

I'm trying to put together a RegEx to split a variety of possible user inputs, and while I've managed to succeed with some cases, I've not managed to cover every case that I'd like to.

Possible inputs, and expected outputs

"1 day" > [1,"day"]
"1day" > [1,"day"]
"10,000 days" > [10000,"days"]


Is it possible to split the numeric and text parts from the string without necessarily having a space, and to also remove the commas etc from the string at the same time?

This is what I've got at the moment

[a-zA-Z]+|[0-9]+


Which seems to split the numeric and text portions nicely, but is tripped up by commas. (Actually, as I write this, I'm thinking I could use the last part of the results array as the text part, and concatenate all the other parts as the numeric part?)

Answer Source

var test = [
    '1 day',
    '1day',
    '10,000 days',
];
console.log(test.map(function (a) {
  a = a.replace(/(\d),(\d)/g, '$1$2'); // remove the commas
  return a.match(/^(\d+)\s*(.+)$/);    // split in two parts
}));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download