1

I'm trying to capture names in a paragraph, and return them as an array. The sentence with the names contains "names are". Example:

The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.

Desired Output:

[ "John", "Jane", "Jen" ]

Attempt

paragraph.match(/names are ([A-Za-z ]+,{0,1} {0,1})+\./)
Emma
  • 1
  • 9
  • 28
  • 53
Sepero
  • 3,751
  • 1
  • 24
  • 22

2 Answers2

1

You could use names are ([^.]+) to match everything until the next period. Then use split to get the names to an array

const str = 'The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.'

const regex = /names are ([^.]+)/,
      names = str.match(regex)[1],
      array = names.split(/,\s*/)

console.log(array)
adiga
  • 28,937
  • 7
  • 45
  • 66
1

You can use split() after matching

let str = `The first sentence. Some second sentence. Third sentence and the names are John, Jane, Jen. Here is the fourth sentence about other stuff.`

let res = str.match(/names are ([A-Za-z ]+,{0,1} {0,1})+\./g)[0].split(/\s+/g).slice(2)
console.log(res)
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51