-3

I have a text box with a bunch of comments, all separated by a specific character string as a means of splitting them to display each comment individually.

The string in question is | but I can change this to accommodate whatever will work. My only requirement is that it is not likely to be a string of characters someone will type in an everyday sentence.

I believe I need to use the split method and possibly some regex but all the other questions I've seen only seem to mention splitting by one character or a number of different characters, not a specific set of characters in a row.

Can anyone point me in the right direction?

  • 3
    Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Heretic Monkey Feb 06 '18 at 19:17

1 Answers1

0

.split() should work for that purpose:

var comments = "this is a comment|and here is another comment|and yet another one";
var parsedComments = comments.split('|');

This will give you all comments in an array which you can then loop over or do whatever you have to do.

Keep in mind you could also change | to something like <--NEWCOMMENT--> and it will still work fine inside the split('<--NEWCOMMENT-->') method.

Remember that split() removes the character it's splitting on, so your resulting array won't contain any instances of <--NEWCOMMENT-->

Tallboy
  • 12,847
  • 13
  • 82
  • 173