JavaScript Regex Syntax Highlighter

Current version: 0.1 (2010-07-04). License: MIT.

Do you want RegexPal-style regex syntax highlighting on your webpages? This library takes care of it for you, so you can spend more time writing powerful regular expressions and less time deciphering them. Currently, JavaScript regexes only are supported. Any regex features not supported by JavaScript are marked as errors, along with some edge cases that cause cross-browser grief. There's a bit more detail in my related blog post.

Sexy examples

Innermost HTML tables

<table\b[^>]*>(?:(?=([^<]+))\1|<(?!table\b[^>]*>))*?</table>

SSN

^(?!000|666)(?:[0-6]\d{2}|7(?:[0-6]\d|7[012]))-(?!00)\d{2}-(?!0000)\d{4}$

ZIP codes

\b[0-9]{5}(?:-[0-9]{4})?\b

Regex with errors

Following are a few examples of the kinds of syntax errors and cross-browser headaches that are detected and flagged in red:

Hello+?? x*+ |? a{1,2}b{2,1} |(?:a|b)* (?=x)* (?<=n) (((((((a)))b.c)d|x(y){65535,}z{65536,}))))
[1-59-6\b-\cX.a-\w!---] \xFF \x \uFF\uFFFF\z\v\\\

Source code

Here's the code running on this page to highlight all of the above regexes:

var regexEls = document.getElementsByClassName("regex"),
    len = regexEls.length,
    el, text, i;

for (i = 0; i < len; i++) {
    el = regexEls[i];
    text = el.textContent || el.innerText;

    // this is where the magic happens
    el.innerHTML = highlightJsReSyntax(text);
}

To see and test this regex highlighting as you type, check out RegexPal (regex tester). Other cool things to do include posting feedback on my blog, and following me on the tweeter.