JavaScript RegEx Tester

by jsumners

HTML

<div id="regexForm"> <strong>/</strong>

    <input id="regexString" size="50"> <strong>/</strong>

    <input id="regexOptions" size="4">
</div>
<div id="sourceForm">
    <textarea id="source" cols="80" rows="10"></textarea>
</div>
<p>Results:</p>
<div id="output"></div>

CSS

#formattedJSON {
    font-family: monospace;
    list-style: none;
    margin: 5px;
}

.jsonArray li,
.jsonObject li {
    margin-left: 2em;
}

li.jsonCloseBracket,
li.jsonOpenBracket {
    display: block;
    font-weight: bold;
    margin-left: 0em;
}

.jsonDisclosure {
    cursor: pointer;
}

.jsonArray,
.jsonObject {}

.jsonKeyName {
    color: green;
    font-weight: bold;
}

.jsonKeyword {
    color: purple;
}

.jsonNumber {
    color: darkslateblue;
}

.jsonString {
    color: red;
}

.jsonKeyNameSeparator,
.jsonSeparator {
    clear: right;
    color: black;
}

JavaScript

$.getScript("https://bitbucket.org/jsumners/formatjson/raw/tip/src/jquery.formatJSON.js")
     .done(function () {
     var $output = $("#output"),
         $regexString = $("#regexString"),
         $regexOptions = $("#regexOptions"),
         $source = $("#source"),
         handler = function () {},
         timer;

     handler = function () {
         if (timer) {
             clearTimeout(timer);
         }

         timer = setTimeout(function () {
             var expr = $regexString.val(),
                 json,
                 options = $regexOptions.val(),
                 regex,
                 results,
                 source = $source.val();

             if (!expr || !source) {
                 return;
             }

             try {
                 regex = new RegExp(expr, options);
             } catch(ex) {
                 console.log(ex.toString());
                 return;
             }

             results = regex.exec(source);
             json = JSON.stringify(results);

             $output.formatJSON({
                 jsonString: json,
                 collapse: false
             })
         }, 500);
     };

     $regexString.on("keyup", handler);
     $regexOptions.on("keyup", handler);
 });