简体   繁体   English

如何删除字符串末尾的换行符?

[英]How to remove the line break at the end of a string?

How do I remove a line break at the end of a string?如何删除字符串末尾的换行符? I can use RegEx or string.indexOf().我可以使用 RegEx 或 string.indexOf()。

What I have so far doesn't work:到目前为止我所拥有的不起作用:

 var message = "first paragraph.\\n\\nNext paragraph.\\n"; var trimMessage = message.lastIndexOf("\\n")==0 ? message.substring(0, message.length-2) : message;

Regex to the rescue:正则表达式来救援:

var trimMessage = message.replace(/\n$/, '');

The $ means "end of input." $表示“输入结束”。

Example:例子:

 var message = "first paragraph.\\n\\nNext paragraph.\\n"; var trimMessage = message.replace(/\\n$/, ''); var pre = document.createElement('pre'); pre.innerHTML = "Message:\\n***" + message + "**\\n\\ntrimMessage = ***\\n" + trimMessage + "***"; document.body.appendChild(pre);

Your use of -2 in your example makes me think you may be dealing with \\r\\n linebreaks, or possibly sometimes \\n and sometimes \\r\\n .您在示例中使用-2使我认为您可能正在处理\\r\\n换行符,或者有时可能是\\n有时是\\r\\n Or if you're going back in time, just \\r (old Mac OS, before the BSD fork).或者,如果您要回到过去,只需\\r (旧的 Mac OS,在 BSD fork 之前)。 To handle all of those, you can use a character class and + meaning "one or more":要处理所有这些,您可以使用字符类和+表示“一个或多个”:

var trimMessage = message.replace(/[\r\n]+$/, '');

I like regular expressions myself:我自己喜欢正则表达式:

var t = message.replace(/[\r|\n|\r\n]$/, '');

In this case, it catches all three forms of a EOL, something I do out of habit.在这种情况下,它会捕获所有三种形式的 EOL,这是我出于习惯所做的。

This is a Javascript solution.这是一个 Javascript 解决方案。

Your code is testing if the newline is at the beginning of the string, not the end.您的代码正在测试换行符是否在字符串的开头,而不是结尾。

var trimMessage = message.length && message.charAt(message.length-1) == "\n" ? message.slice(0, -1) : message;

The message.length test at the beginning prevents trying to access a negative position if the string is empty.如果字符串为空,开头的message.length测试可防止尝试访问负数位置。

Regex is nice, but it's tough to wrangle and you can do the same thing with simpler JS.正则表达式很好,但它很难争论,你可以用更简单的 JS 做同样的事情。

If you KNOW there is a newline at the end of the string:如果您知道字符串末尾有一个换行符:

var foo = "hello, world\n";
var bar = foo.substring(0, foo.length-1);

Or just use indexOf:或者只使用 indexOf:

var foo = "hello, world\n";
var bar = (foo.indexOf("\n") != -1) ? foo.substring(0, foo.indexOf("\n")) : foo;

This works fine.这工作正常。 You can add a ternary operator to check if it is the last line or not.您可以添加一个三元运算符来检查它是否是最后一行。

for(let i = 1; i <= 10; i++) {
    result +=`${table} x ${i} = ${table * i} ${i === 10? "":"\n" }`;
}

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

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