4

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.

Daft
  • 10,277
  • 15
  • 63
  • 105

2 Answers2

6

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can find the answer below.

let oldString = '[foo faa] [faaaa] [feee foo] [fu]';
let newStringArr = oldString.split(" ").join(',').replace(/\],\[/gi, "],d[").split(",d")
console.log(newStringArr);

document.write(JSON.stringify(newStringArr))
cangokceaslan
  • 467
  • 1
  • 5
  • 12