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.

13 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..

  4. mario sison

    spent days trying to figure out matching between characters that have multi line & this man comes up with just [^]+ which gets any char in between, a lot of people always say they know their stuff but a few people really know their stuff; this man is one of them.

  5. mario sison

    this removes everything except a square empty box.
    [^\\u25A1]+
    this removes everything up to & including the empty square box & the space after it.
    [^\\u25A1]+\\u25A1\\s+

Leave a Reply

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