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' ]
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)
#{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 #If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With