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

0

1 Answer 1

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\]) */)
);

Sign up to request clarification or add additional context in comments.

2 Comments

Can you include actual spaces around the [SPACE] in regex, to get the desired output array as specified in the question?
Oh, thanks, I missed that, have to match the spaces normally so they aren't present in the output

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.