javascript - Split string and keep demiliter with following text


Keywords:javascript 


Question: 

I have a long string of text that I want to split into an array by the strings "#", "##" and "###".

I can do this with:

const text = "### foo ## foo # foo ### foo ## foo ### foo ### foo ### foo"

text.split(/#{1,3}/g)

Output:

 [ '',
          ' foo ',
          ' foo ',
          ' foo ',
          ' foo ',
          ' foo ',
          ' foo ',
          ' foo ',
          ' foo' ]

However this removes the hashtags, which I still need. I can also keep the hashtags, but they are just added as elements to the array, which is not desirable either.

text.split(/(#{1,3})/g)

Output:

[ '',   '###',   ' foo ',   '##',   ' foo ',   '#',   ' foo ', '###',   ' foo ',   '##',   ' foo ',   '###',   ' foo ',   '###',   ' foo ',   '###',   ' foo' ]

How can I split the text so that the text after the hashtags is included in the array element after the hashtag? So that the result would be like this.

Wanted result:

[ '### foo ',   '## foo ',   '# foo ',   '### foo ',   '## foo ',   '### foo ',   '### foo ',   '### foo' ]

1 Answer: