Reputation: 9
I'm doing an add on for google docs and in the JavaScript code, I want to search specific word("minutes"for example) and the previous word of this word("10" for example) and then I want to calculate the sum of all the minutes that I have.
Upvotes: 0
Views: 227
Reputation: 268
I think this may be what you are after.
var text = 'Lorem ipsum dolor sit amet 10 minutes, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 30 minutes consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est 60 minutes laborum.';
var re = new RegExp(/(\d+)\s+(?:minutes)/,'gm');
var sum = 0;
var val = 0;
while ((val = re.exec(text))) {
sum += parseInt(val[1]);
}
console.log('sum', sum);
Upvotes: 1