Ashish Kumar Ashish Kumar - 1 year ago 45
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"]


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.

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