Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from the textarea

Tags:

javascript

How do I create a function that extracts the text from the textarea and divides it into the individual words and puts all the words in an array?

<body>

 <textarea name="text" id="" cols="30" rows="10" id="textarea"></textarea>
 <button id="button">Click</button>


 <script src="script.js"></script>
</body>

This is what i got :P Been stuck for a while now. Can't figure out what to do. Pleas help.

 var btn = document.getElementById("button");
 btn.addEventListener("click", getText);

 function getText(){

 }

</script>
like image 908
Eirik Vattøy Avatar asked Mar 16 '26 04:03

Eirik Vattøy


1 Answers

You have 80% done :-)

Now you need to get the value from the textarea, replace the spaces with this regexp /\s+/ (this is just to replace consecutive spaces) and then split the text by ' ' (single space)

var btn = document.getElementById("button");
btn.addEventListener("click", getText);

var array;

function getText() {
  var textarea = document.getElementById('text');
  array = textarea.value.replace(/\s+/g, ' ').split(' ').filter((e) => e.length > 0);
  
  console.log(array);
}
<textarea name="text" id="text" cols="30" rows="10" id="textarea">Hello           World</textarea>
<button id="button">Click</button>

See? now you're getting the values into an array.

UPDATED: According to @phil the g modifier is necessary to avoid inconsistent with new lines at first position.

like image 86
Ele Avatar answered Mar 18 '26 19:03

Ele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!