Skip to content Skip to sidebar Skip to footer

Wrapping Conditional Blocks In A Contenteditable Div Using Regex

contenteditable div id = 'board_code_dup' cout<<'something'; if( a>b && b

Solution 1:

Try

var stack = [], regex1 = /^(if|else|else\s+if).*{$/, regex2 =  /^(if|else|else\s+if).*$/, closing = /^}$/;

$('#board_code_dup').children().each(function(){
    var $this = $(this), text = $.trim($this.text());

    if(regex1.test(text)){
        stack.unshift(this);
    } elseif(closing.test(text)){
        $(stack.shift()).nextUntil(this).addBack().add(this).wrapAll('<div class="condBlock" />')
    } elseif(regex2.test(text)){
        $(this).next().addBack().wrapAll('<div class="condBlock" />')
    }
})

Demo: Fiddle

Post a Comment for "Wrapping Conditional Blocks In A Contenteditable Div Using Regex"