2

I am trying to find the first word of every paragraph using a regex in JavaScript. I am doing so with the following:

function getFirstWordInParagraph(content) {
  return content.match(/\n\S+/gi);
}

The problem here is I cannot figure how to match the new line character, but exclude it from the result. Is this possible with a JavaScript regex?

Note: the function does not account for the first word of the first paragraph.

Evan Emolo
  • 1,660
  • 4
  • 28
  • 44

1 Answers1

4

There's a special construct for "position at the start of a line": The ^ anchor (if you set the MULTILINE option):

function getFirstWordInParagraph(content) {
  return content.match(/^\S+/gm);
}

You don't need the i option since nothing in your regex is case-sensitive.

This solution will also find the word at the very start of the string.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561