[SOLVED] JS string invert match (RegEx)

Issue

I have a string and I want to divide the parts that match a regex from rest of the text.

var str = 'Lorem ipsum [asdasd]dolor si[@@]c amet';
var brackets = str.match(/\[[\s\S]+\]);  // ['[asdasd]', '[@@]']
var lipsum = ???                         // ['Lorem ipsum ', 'dolor si', 'c amet']

Is there any way to do this natively?

Solution

Instead of using match, you can use split with a pattern matching from [...] in a capture group and get all the matches in one array.

var str = 'Lorem ipsum [asdasd]dolor si[@@]c amet';
console.log(str.split(/(\[[^\][]*])/));

If you want separate matches for the bracket and lipsum, you might use the same pattern with for example reduce:

const str = '[Lorem ipsum [asdasd]dolor si[@@]c amet';
const res = str
    .split(/(\[[^\][]*])/)
    .reduce((a, c) => {
    /^\[[^\][]*]$/.test(c) ? a.brackets.push(c) : a.lipsum.push(c); return a;
}, {brackets:[], lipsum:[]})

console.log(res);

Answered By – The fourth bird

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *