14

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

5
  • 7
    any attempts?... Commented Mar 16, 2017 at 7:36
  • And what if the string looks like foo1bar2xyz3moo? Commented Mar 16, 2017 at 7:39
  • @AvinashRaj sorry i could not find the exactly same q&a, and I'm not really familiar with Javascript :( Commented Mar 16, 2017 at 7:41
  • @WiktorStribiżew string always comes first and the number second, without space as delimiter. Commented Mar 16, 2017 at 7:42
  • Then you need to use a regex-based split with a positive lookahead with a digit matching pattern. Commented Mar 16, 2017 at 7:46

3 Answers 3

43

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. */
Sign up to request clarification or add additional context in comments.

Comments

20

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])

1 Comment

Perfect one-liner. This should be the accepted answer.
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

3 Comments

An explanation would be in order.
@Vindhyachal Kuma why we need item.replace(/\'/g, '')
to remove all single quote from string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.