Regex replace

by SpAm

HTML

<input type="text" id="replaceThis"/>
<pre contenteditable="true" class="dis" id="json" style="border:1px solid black;height:302px;padding:5px;overflow-y:scroll;">
    Hello
</pre>
Start script:
<pre contenteditable="true" class="dis" id="startScript" style="border:1px solid black;height:102px;padding:5px;overflow-y:scroll;">
</pre>
Match script:
<pre contenteditable="true" class="dis" id="script" style="border:1px solid black;height:102px;padding:5px;overflow-y:scroll;">
</pre>
<button type="button" id="apply">Apply</button>

CSS

input[type=text], textarea {
    width:100%;
    margin:5px 1px;
}

textarea {
    height:300px;
}

.foo {
    background-color:red;
}

JavaScript

function getReg() {
	var reg = 
    new RegExp("(" + $('#replaceThis').val() + ")", "g");
    return reg;
}


function highlight() {
var text = $('#json').text();
var reg = getReg();
var found = 
    text.replace(
        reg, "<span class='foo'>$1</span>"
    );
    
$('#json').html(found);	
}


function applyScript() {
eval($('#startScript').text());
var text = $('#script').text();
var func = "window.process = function(sub) {" + text + "}";
eval(func);
var text = $('#json').text();
var reg = getReg();
    while(match=reg.exec(text)) {
        text = text.substring(0, match.index) + process(match) + text.substring(match.index+match[0].length);
    }
$('#json').text(text);
highlight();
}

$('#replaceThis').keyup(highlight);
$('#json').keyup(highlight);
$('#global').change(highlight);
$('#apply').click(applyScript);








//new RegExp($(this).val(), "g")