Waltari
Waltari

Reputation: 1249

Split string and keep demiliter with following text

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' ]

Upvotes: 2

Views: 271

Answers (1)

ctwheels
ctwheels

Reputation: 22817

Code

See regex in use here

#{1,3}[^#]+

Use the above regex with the JavaScript match() function

var str = "### foo ## foo # foo ### foo ## foo ### foo ### foo ### foo";
var matches = str.match(/#{1,3}[^#]+/g);
console.log(matches)


Explanation

  • #{1,3} Match between 1 and 3 of the number sign (or whatever you want to call the symbol) # character literally
  • [^#]+ Match 1 or more of any character not present in the set #

Upvotes: 11

Related Questions