Regular Expression can be used in the standard match function to extract the first line of a multiline string, e.g. content of a source file.

"This is the first line.\n This is the second line.".match(/^.*$/m)[0];

// => "This is the first line."

Explain: match(/^.*$/m)[0]

  • ^ : begin of line
  • . : any char (.), 0 or more times
  • $ : end of line.
  • m : multiline mode (. acts like a \n too)
  • [0] : get first position of array of results

It works with Windows’ CRLF end of line sequence too.

"This is the first line.\r\n This is the second line.".match(/^.*$/m)[0];

// => "This is the first line."

Share This