最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get text from the textarea - Stack Overflow

programmeradmin4浏览0评论

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>

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>
Share Improve this question asked Jan 29, 2018 at 1:41 Eirik VattøyEirik Vattøy 1751 gold badge2 silver badges14 bronze badges 1
  • How would you define a "word"? What separates "words"? Once you can define that, you can simply use document.querySelector('textarea').value.split(wordDelimeter) – Phil Commented Jan 29, 2018 at 1:45
Add a ment  | 

2 Answers 2

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论