Ashish Kumar
Ashish Kumar

Reputation: 136

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.

Upvotes: 0

Views: 126

Answers (2)

guest271314
guest271314

Reputation: 1

You can use String.prototype.match() with RegExp /\d+\s+\w+/g to match one or more digit characters followed by one or more space characters followed by one or more word characters

var str = "3 rolls 7 buns 9 bars 7 cooks";
var res = str.match(/\d+\s+\w+/g);
console.log(res);

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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.

Upvotes: 2

Related Questions