简体   繁体   中英

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. 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.

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

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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