[SOLVED] JS string invert match (RegEx)


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?


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';

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
    .reduce((a, c) => {
    /^\[[^\][]*]$/.test(c) ? a.brackets.push(c) : a.lipsum.push(c); return a;
}, {brackets:[], lipsum:[]})


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 *