Javascript 从文本区域中删除最后一个“\n”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3084708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:14:24  来源:igfitidea点击:

Remove the last "\n" from a textarea

javascriptnewline

提问by randomwebdev

How to remove the last"\n" from a textarea?

如何从文本区域中删除最后一个“\n”?

回答by aarti

Only remove the last newline characters (\n):

只删除最后一个换行符 ( \n):

verses1 = "1\n222\n"
verses1.replace(/\n$/, "")
// "1\n222"

verses2 = "1\n222\n\n"
verses2.replace(/\n$/, "")
// "1\n222\n"

Only all the last newlines (\n):

只有所有最后的换行符 ( \n):

verses = "1\n222\n\n"
verses.replace(/\n+$/, "")
// "1\n222"

https://regexr.com/4uu1r

https://regexr.com/4uu1r

回答by John Boker

from http://en.wikipedia.org/wiki/Trim_%28programming%29

来自http://en.wikipedia.org/wiki/Trim_%28programming%29

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
};

That will add a trim function to string variables that will remove whitespace from the beginning and end of a string.

这将向字符串变量添加一个修剪函数,该函数将从字符串的开头和结尾删除空格。

With this you can do stuff like:

有了这个,你可以做这样的事情:

var mystr = "this is my string   "; // including newlines
mystr = mystr.trim();

回答by Ben Taliadoros

$.trim()should do the trick!

$.trim()应该可以解决问题!

It trims whitespace and newline characters from the beginning and ending of the specified string.

它从指定字符串的开头和结尾修剪空白和换行符。

回答by creftos

I personally like lodash for trimming newlines from strings. https://lodash.com/

我个人喜欢 lodash 从字符串中修剪换行符。https://lodash.com/

_.trim(myString);