如何删除字符串末尾的换行符? [英] How to remove the line break at the end of a string?
本文介绍了如何删除字符串末尾的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何删除字符串末尾的换行符?我可以使用 RegEx 或 string.indexOf().
How do I remove a line break at the end of a string? I can use RegEx or string.indexOf().
到目前为止我所拥有的不起作用:
What I have so far doesn't work:
var message = "first paragraph.
Next paragraph.
";
var trimMessage = message.lastIndexOf("
")==0 ? message.substring(0, message.length-2) : message;
推荐答案
正则表达式来拯救:
var trimMessage = message.replace(/
$/, '');
$
表示输入结束".
示例:
var message = "first paragraph.
Next paragraph.
";
var trimMessage = message.replace(/
$/, '');
var pre = document.createElement('pre');
pre.innerHTML =
"Message:
***" + message + "**
trimMessage = ***
" + trimMessage + "***";
document.body.appendChild(pre);
您在示例中使用 -2
让我觉得您可能正在处理
换行符,或者有时可能是
有时
.或者,如果您要回到过去,只需
(旧的 Mac 操作系统,在 BSD 分支之前).要处理所有,您可以使用字符类和 +
表示一个或多个":
Your use of -2
in your example makes me think you may be dealing with
linebreaks, or possibly sometimes
and sometimes
. Or if you're going back in time, just
(old Mac OS, before the BSD fork). To handle all of those, you can use a character class and +
meaning "one or more":
var trimMessage = message.replace(/[
]+$/, '');
这篇关于如何删除字符串末尾的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文