Ashish Kumar Ashish Kumar - 9 months ago 33
Javascript Question

javascript ; regex split string with number + rest of the string till next number

I checked all the post and could not find correct solution so asking this question.

I have a string like " 3 rolls 7 buns 9 bars 7 cooks" and output that i am looking for is something like ["3 rolls","7 buns","9 bars","7 cooks"]

thanks.

Answer Source

You can use regular expression to achieve this,

var result = "3 rolls 7 buns 9 bars 7 cooks".split(/\s(?=\d)/);
conosole.log(result); //["3 rolls", "7 buns", "9 bars", "7 cooks"]

The regex concept used here is positive look ahead.