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

How to handle tabs, line breaks and whitespace in a text in JavaScript?


To hand tabs, line breaks and whitespace in a text, use the whitespace property in JavaScript. Set the values normal, nowrap, pre, etc. On setting pre, it works like the <pre> tag. Text will only wrap on line breaks.

Example

You can try to run the following code to learn how to work with the whitespace property in JavaScript

<!DOCTYPE html>
<html>
   <head>
      <style>
         #box {
            width: 300px;
            height: 100px;
            border: 2px solid black;
            background-color: gray;
         }
      </style>
   </head>
   <body>
      <button onclick="display()">Set</button>
      <div id="box">
         This is Demo Text.
         This is Demo Text.
         This is Demo Text.
         This is Demo Text.
         This is Demo Text.
      </div>
      <script>
         function display() {
            document.getElementById("box").style.whiteSpace = "pre";
         }
      </script>
   </body>
</html>