0

I have string like this one:

This is a text [SPACE] and this also text [SPACE] more text [SPACE] here text

My goal is to create array like this:

['This is a text', '[SPACE]', 'and this also text', '[SPACE]', 'more text', '[SPACE]']

Or like this

['This is a text', 'SPACE', 'and this also text', 'SPACE', 'more text', 'SPACE']

I've tried to split it like this .split('['), but it's not exactly what I'm looking for

NickD
  • 59
  • 1
  • 6

1 Answers1

2

Match and capture [SPACE] in a regular expression. Captured groups inside a split will be included in the output array, so that's exactly what you should aim for here. To omit the spaces around the [SPACE], just match them normally, outside the capture group, and they won't be present in the output:

const input = 'This is a text [SPACE] and this also text [SPACE] more text [SPACE] here text';
console.log(
  input.split(/ *(\[SPACE\]) */)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320