13

I'd like to split strings like

'foofo21' 'bar432' 'foobar12345'

into

['foofo', '21'] ['bar', '432'] ['foobar', '12345']

Is there an easy and simple way to do this in JavaScript?

Note that the string part (for example, foofo can be in Korean instead of English).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bossam
  • 744
  • 2
  • 9
  • 24

3 Answers3

40

Second solution:

var num = "'foofo21".match(/\d+/g);
// num[0] will be 21

var letr =  "foofo21".match(/[a-zA-Z]+/g);
/* letr[0] will be foofo.
   Now both are separated, and you can make any string as you like. */
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RajeshP
  • 401
  • 2
  • 4
  • 2
17

You want a very basic regular expression, (\d+). This will match only digits.

whole_string="lasd行書繁1234"
split_string = whole_string.split(/(\d+)/)
console.log("Text:" + split_string[0] + " & Number:" + split_string[1])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BioGenX
  • 402
  • 3
  • 11
13

Check this sample code

var inputText = "'foofo21' 'bar432' 'foobar12345'";
function processText(inputText) {
        var output = [];
        var json = inputText.split(' '); // Split text by spaces into array

        json.forEach(function (item) { // Loop through each array item
            var out = item.replace(/\'/g,''); // Remove all single quote '  from chunk
                out = out.split(/(\d+)/); // Now again split the chunk by Digits into array
                out = out.filter(Boolean); // With Boolean we can filter out False Boolean Values like -> false, null, 0 
                output.push(out);
        });
            
        return output;
}

var inputText = "'foofo21' 'bar432' 'foobar12345'";

var outputArray = processText(inputText);

console.log(outputArray); Print outputArray on console 

console.log(JSON.stringify(outputArray); Convert outputArray into JSON String and print on console

Vikas Kandari
  • 1,612
  • 18
  • 23
Vindhyachal Kumar
  • 1,713
  • 2
  • 23
  • 27