简体   繁体   English

JavaScript-如果以前没有文本,如何从textarea中删除新行?

[英]JavaScript - How to remove new line from textarea if no text exists before?

I have a textarea and I want to remove new lines from it, if the return key is pressed, without writing any text. 我有一个textarea ,如果要按回车键,而又不写任何文本,我想从其中删除新行。 I tried this, but it did not work: 我试过了,但是没有用:

function keypress(id) {
  $("#"+id).keypress(function(event) {
    $("#"+id).val().replace(/\n/g, "");
  });
}

Try 尝试

function keypress(id) {
    $("#" + id).keyup(function (event) {
        $(this).val($(this).val().replace(/^\s*(\n)\s*$/, ''))
    });
}

Demo: Fiddle 演示: 小提琴

Why don't you use the Javascript trim method. 为什么不使用Javascript trim方法。

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim 来自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

The trim() method removes whitespace from both ends of a string. trim()方法从字符串的两端删除空格。 Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). 在这种情况下,空白是所有空白字符(空格,制表符,不间断空格等)和所有行终止符(LF,CR等)。

function keypress(id) {
   $("#"+id).keypress(function(event) {
      $("#"+id).val().trim();
   });
}

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

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