Computer >> Computer tutorials >  >> Programming >> Javascript

How to use a line break in array values in JavaScript?


To add a line break in array values for every occurrence of ~, first 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!

This will add line breaks like the following for ~ occurrence:

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

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <h2>Adding line break</h2>
      <script>
         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> ");
         document.write("<br><br>"+res);
      </script>
      <p>Each occurence of ~ adds a line break above.</p>
   </body>
</html>