2

我正在尝试使用 JavaScript 中的正则表达式查找每个段落的第一个单词。我正在这样做:

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

这里的问题是我不知道如何匹配换行符,但将其从结果中排除。使用 JavaScript 正则表达式可以做到这一点吗?

注意:该函数不考虑第一段的第一个单词。

4

1 回答 1

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.

于 2013-10-12T20:20:02.107 回答