2

I've got a string:

"My cow gives milk, my cow always gives milk". 

I want to extract the text between "cow" and "milk", which will give me

["gives", "always gives"].

I've tried string.match('cow (.*?) milk'), but it gives me

["cow gives milk", "gives"].
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
lucahuy
  • 790
  • 2
  • 9
  • 22
  • Your answer(s) are [here](https://stackoverflow.com/a/40782646/3832970). You have no overlapping matches here, only several non-overlapping ones. – Wiktor Stribiżew Jun 09 '19 at 10:25

1 Answers1

2

You can use matchAll and then take the groups only

let str = "My cow gives milk, my cow always gives milk"
let op = str.matchAll(/cow (.*?) milk/g)

let final = [...op].map( value => value[1] )

console.log(final)

Alternative

const regexp = RegExp('cow (.*?) milk','g');
const str = "My cow gives milk, my cow always gives milk"

while ((matches = regexp.exec(str)) !== null) {
  console.log(`Matched value :-  ${matches[1]}`);
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 1
    does not have the best [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll#Browser_compatibility) though – Aprillion Jun 09 '19 at 07:22
  • @Aprillion you can use `exec` in that case, see the update, – Code Maniac Jun 09 '19 at 07:29