Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string at every occurrence of character, but keep character in new array

Tags:

javascript

If I have a string which looks like this:

 let oldString = '[foo faa] [faaaa] [feee foo] [fu]';

How can I split it to return the following:

let newArr = ['[foo faa]','[faaaa]','[feee foo]','[fu]'];

So I would like to split it at every ']' character, but keep to that character in the new array.

I've tried oldString.split(']') but it does not return the array in the shape I was expecting.

like image 593
Daft Avatar asked Oct 28 '25 04:10

Daft


1 Answers

You could match the parts with the left and right delimiter.

let string = '[foo bar] [faaaa] [feee] [fu]',
    array = string.match(/\[[^\]]+\]/g);

console.log(array);
like image 53
Nina Scholz Avatar answered Oct 30 '25 14:10

Nina Scholz