Languages
[Edit]
EN

JavaScript - convert textarea lines into array

0 points
Created by:
Jan-Alfaro
711

In this article, we would like to show you how to convert textarea lines into an array using JavaScript.

Quick solution:

// get the value of textarea by id:
var textareaValue = document.querySelector('#textareaId').value;

// split value of textarea by \n (it will be converted into array):
var linesArray = textareaValue.split('\n');

 

Preview

JavaScript - convert textarea lines into array
JavaScript - convert textarea lines into array

Practical example

In this example, we get handle to textarea by id using document.querySelector() method. Then we take its value and we split it into an array by new line character (\n) using split() method.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    // ...
  </style>
</head>
<body>
  <textarea id='myTextArea'
            rows='10'
            cols='50'></textarea>
  <br>
  <button onclick="handleClick()">Get textarea value</button>
  <script>
    
    function handleClick() {
        // get the value of textarea:
        var textareaValue = document.querySelector('#myTextArea').value;

        // split value of textarea by \n (it will be converted into array):
        var linesArray = textareaValue.split('\n');
        console.log(JSON.stringify(linesArray));
    }

  </script>
</body>
</html>

 

See also

  1. JavaScript - get textarea field value

References

  1. String.prototype.split() - JavaScript | MDN

Alternative titles

  1. JavaScript - convert textarea value into array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join