1

I a splitting the input of a textarea into seperate lines like this.

const lines = $('#myTextarea').val().split('\n');

However I would also split it when the user enters \n but this is somehow ignored.

So when the user's input in the textarea is:

first line \n second line
third line
fourth line

I expect to have an array with [first line,second line, third line, fourth line]

but instead I get[first line \n second line, third line, fourth line]

Always Helping
  • 14,316
  • 4
  • 13
  • 29
zlZimon
  • 2,334
  • 4
  • 21
  • 51
  • 2
    From link: use a regex: `$("textarea").val().split(/\n|\\n/)` (you may want/need to add whitespace trimming to the regex or after) – freedomn-m Aug 22 '20 at 10:46

1 Answers1

0

You can use this simple regex - /\s+/ along with .trim() function to get your desired output and to make sure each space or multiple spaces are converted in to each line when using split()

Live Demo:

function getText() {
  let lines = $('#myTextarea').val().trim().split(/\s+/);
  console.log(lines)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="myTextarea" cols="50" rows="4" placeholder="Enter text"></textarea>
<br>
<button onclick="getText()">
Split 
</button>
Always Helping
  • 14,316
  • 4
  • 13
  • 29