[英]How to trim text inside textarea
I have a textarea, I would like to trim the text inside it and display the result.我有一个文本区域,我想修剪其中的文本并显示结果。
Example:例子:
" 1234 " “1234”
becomes变成
"1234" “1234”
However for some reason it doesn't trim the text, and it returns nothing.但是由于某种原因,它不会修剪文本,也不会返回任何内容。
HTML HTML
<form id="form1">
<textarea id="text-area" rows="20" cols="50" placeholder="text here..."></textarea><br>
<button class="button" onclick="myFunc()">Sumbit</button>
</form>
JS JS
function myFunc(){
var getText = document.getElementById("text-area").textContent;
var result = getText;
result.trim();
document.getElementById("text-area").textContent = result;
}
No JQuery please请不要 JQuery
It is failing because, .trim
does not mutates the actual string.它失败了,因为.trim
不会改变实际的字符串。 It returns a new string.它返回一个新字符串。 All you need to do is result = result.trim();
您需要做的就是result = result.trim();
function myFunc(){ var result = document.getElementById("text-area").value; console.log(result); result = result.trim(); console.log(result); document.getElementById("text-area").value = result }
<textarea id="text-area" rows="20" cols="50" placeholder="text here..."></textarea> <br> <button class="button" onclick="myFunc()">Sumbit</button>
You need to use the value
property, not textContent
.您需要使用value
属性,而不是textContent
。 And trim()
returns a new string rather than modifying the old one.并且trim()
返回一个新字符串,而不是修改旧字符串。 Also you can make the code much more concise.您还可以使代码更简洁。
Demo:演示:
function myFunc() { var ta = document.getElementById("text-area"); ta.value = ta.value.trim(); }
<textarea id="text-area" rows="20" cols="50" placeholder="text here..."></textarea><br> <button class="button" onclick="myFunc()">Submit</button>
(Note: I removed the form tags so it won't submit the form, and so you can see the result of the trim operation when you press Submit. I also corrected the typo - Sumbit
should be Submit
. (注意:我删除了表单标签,所以它不会提交表单,所以当你按下提交时你可以看到修剪操作的结果。我还纠正了错字 - Sumbit
应该是Submit
。
result.trim()
returns a new string, it doesn't modify the existing one. result.trim()
返回一个新字符串,它不会修改现有字符串。
document.getElementById("text-area").textContent = result.trim();
Try this instead:试试这个:
function myFunc(){
var getText = document.getElementById("text-area").textContent;
document.getElementById("text-area").textContent = getText.trim();
}
trim method doesn't affect the string it was called on. trim 方法不会影响调用它的字符串。 It returns the trimmed string.它返回修剪后的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.