Match any character including new line in Javascript Regexp

It seems like the dot character in Javascript’s regular expressions matches any character except new line and no number of modifiers could change that. Sometimes you just want to match everything and there’s a couple of ways to do that.

You can pick an obscure character and apply a don’t match character range with it ie [^`]+. This is not true match any character though. Or you can try [.\r\n]+ which doesn’t seem to work at all. (?:\r|\n|.)+ works fine, but as you’ll find out soon, it is notoriously slow as each time you use it, you are creating a new 3 way branching point because of the brackets.

The perfect way I’ve found is actually a nicer variation of the first idea:
[^]+
Which means ‘don’t match no characters’, a double negative that can re-read as ‘match any character’. Hacky, but works perfectly.

9 thoughts on “Match any character including new line in Javascript Regexp

  1. Pingback: code.gnysek.pl » Blog Archive » JavaScript: dowolny znak włącznie ze znakiem nowej linii

  2. Pingback: Steve Hannah: This week » Javascript matching all characters including new line

  3. Aalok

    Works perfectly!
    I had to do search and replace so I modified the code as .replace(//mgi, “”)
    Thanks again..

Leave a Reply

Your email address will not be published. Required fields are marked *