EN
JavaScript - convert textarea lines into array
0
points
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
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>