Skip to content Skip to sidebar Skip to footer

How Do I Match Everything Except Matched Value?

I have this regex: /(\[.*?\])/g Now I want to change that regex to matches everything except current-matches. How can I do that? For example: Current regex: here is some text [

Solution 1:

Match what's inside or capture what's outside

\[.*?\]|([^[]+)

See demo at regex101

Demo:

var str = 'here is some text [anything123][/21something] and here is too [sometext][/afewtext] and here';

var regex = /\[.*?\]|([^[]+)/g;
var res = '';

// Do this until there is a matchwhile(m = regex.exec(str)) {
    // If first captured group presentif(m[1]) {
        // Append match to the result string
        res += m[1];
    }
}

console.log(res);
document.body.innerHTML = res; // For DEMO purpose only

Post a Comment for "How Do I Match Everything Except Matched Value?"