How do I split a string, breaking at a particular character in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To split a string on every occurrence of ~, split the array. After splitting, add a line break i.e. <br> for each occurrence of ~.

For example,

This is demo text 1!~This is demo text 2!~~This is demo text 3!

After the split and adding line breaks like the following for ~ occurrence −

This is demo text 1!
This is demo text 2!
This is demo text 3!


Let’s see the complete example

Live Demo

<!DOCTYPE html>
   <h2>Adding line break</h2>
      var myArray = 'This is demo text 1!~This is demo text 2!~
                     ~This is demo text 3!~This is demo text 4!~
                     ~This is demo text 5!';
      document.write("Original Array: " +myArray);

      var brk = myArray.split('~');
      var res = brk.join(" <br> ");

      <p>Each occurrence of ~ adds a line break above.</p>
Published on 29-Jan-2018 15:20:07