Feed Sign in with OpenID OpenID

Simon Willison’s Weblog

Matching newlines in JavaScript

Just a quick note: the . character in a JavaScript regular expression will never match a newline character. If you want to match any character including newlines you can use the [\s\S] character class instead, which means “any character that’s either whitespace or not whitespace”.

This differs from both Python and Perl, where regular expression flags can be used to alter the behaviour of the . character (re.DOTALL and /s respectively).

This tip courtesy of the denizens of #javascript on Freenode.

This is Matching newlines in JavaScript by Simon Willison, posted on 20th September 2004.

View blog reactions

Next: Python2.4 highlights

Previous: Browser innovation is alive and well

5 comments

  1. I thought I'd be a Smart Guy and refute your findings with the oft-forgotten RegExp.multiline property, but I quickly found out that it only changes the meaning of ^ and $.

    David Lindquist - 20th September 2004 23:35 - #

  2. Not to say *tisk-tisk* or anything Simon, but this is identical to how PHP handles regular expressions by default. ;)

    But I do sympathize with how frustrating this behaviour can be, especially when dealing with possibly corrupted data. For example, whenever I parse XML through PHP I now force myself to include preg_replace( "/>\s*</", '><', $xml_str ); before any parsing takes place. These facts of regular expressions are just painful concepts that must be bludgeoned into our heads.

    Stephen - 23rd September 2004 22:47 - #

  3. Instead of [\s\S] you may also use [^] to match any char, including newlines.

    Udo Borkowski - 13th December 2005 08:08 - #

  4. Note that the dot in IE does match the carriage return character, but not in for instance Firefox or Opera.

    Tino Zijdel - 23rd January 2006 22:19 - #

  5. Thank you + Freenode denizens

    Suresh V - 5th May 2006 11:21 - #

Comments are closed.

Previously hosted at http://simon.incutio.com/archive/2004/09/20/newlines

A django site