Reputation: 136
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
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
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