JSFiddle - React, Tailwind, and code Playground

by austinfrance

JavaScript

function parseBraces(text) {
    var matches = [], brace = 0, match = {};
    for (var i = 0; i < text.length; i++) {
        if (text[i] == '\\') { 
            i++;
            continue; 
        }
        if (text[i] == '{') {
            if (brace == 0) match.start = i;
            brace ++;
        }
        if (text[i] == '}' && brace > 0 && --brace == 0) {
            match.end = i;
            match.length = i - match.start + 1;
            match.value = text.substr(match.start, match.length);
            matches.push(match);
            match = {};
        }
    }
    return matches;
}

console.dir(parseBraces(
    "{} {{{{x}}}} {{{}}} This {is} a escaped \\{ brace, lone } test {for {nexsted {braces}}}"
    ));