简体   繁体   中英

Get text from the textarea

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>

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.

function getText(){
   var text = document.getElementById("textarea").value;
   var words = text.split(/\s+/);
   return words;
}

The value gets text from textarea and Split breaks text into words using spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM