Categories
JavaScript Answers

How to convert a textarea’s string value to a JavaScript array separated by new lines?

Spread the love

Sometimes, we want to convert a textarea’s string value to a JavaScript array separated by new lines.

In this article, we’ll look at how to convert a textarea’s string value to a JavaScript array separated by new lines.

How to convert a textarea’s string value to a JavaScript array separated by new lines?

To convert a textarea’s string value to a JavaScript array separated by new lines, we can get the value of the text area.

Then we call split on the string with '\n' to split it by the new line character into an array.

For instance, we write:

<textarea></textarea>

to add a text area.

Then we write:

const textarea = document.querySelector("textarea");
textarea.onchange = (e) => {
  const arr = e.target.value.split('\n')
  console.log(arr)
}

to listen to the change event by setting the textarea.onchange property to a function that gets the input value from e.target.value.

Then we call split with '\n' to split the string by the newline character into an array.

Conclusion

To convert a textarea’s string value to a JavaScript array separated by new lines, we can get the value of the text area.

Then we call split on the string with '\n' to split it by the new line character into an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *