简体   繁体   English

从文本区域获取文本

[英]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. 这就是我得到的:P现在被卡住了一段时间。 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 :-) 您完成了80%:-)

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) 现在您需要从textarea中获取值,用此regexp /\\s+/替换空格(这只是替换连续的空格),然后用''(单个空格)分割文本

 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. 更新 :根据@phil ,必须使用g修饰符以避免与第一行的新行不一致。

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. value从textarea获取文本, Split使用空格将文本拆分为单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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