Remove line-breaks and spaces from textarea

微笑、不失礼 提交于 2019-12-21 06:17:55

问题


<textarea rows='5' cols='50' id='content'></textarea>
<input type='button' value='Extract Text' onclick='someFunction()'/>

Assume these two html elements. My problem is the following:

Let's say that the user enters into the textarea field something like this, exactly as typed. With all line breaks and spaces. (And yes, this is Python :P)

if (...):  
   print "Hello everyone!"
else:
   print "Dudes help me out!"

My objective is to make a JavaScript function which removes all the spaces and line breaks (typed with 'Enter') and returns a space-less string. Something like "ThisIsASampleText". I've used document.getElementById('content').value and myString.replace(/\s+/g, '') to remove spaces. Can't make it work. Any ideas?

Best Regards


回答1:


Here's a live demo of how to use the regex you described to remove all whitespace in the text from your textarea:

function someFunction() {
    var output = document.getElementById("content").value;
    output = output.replace(/\s/g, "") 
    document.getElementById("output").innerHTML = output;
}
<textarea rows='5' cols='50' id='content'></textarea>
<input type='button' value='Extract Text' onclick='someFunction()'/>
<div id="output"></div>

JSFiddle Version: https://jsfiddle.net/afy5v66x/1/



来源:https://stackoverflow.com/questions/32039740/remove-line-breaks-and-spaces-from-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!