问题
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.\n\nNext paragraph.\n";
var trimMessage = message.lastIndexOf("\n")==0 ? message.substring(0, message.length-2) : message;
回答1:
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. Or if you're going back in time, just \r (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(/[\r\n]+$/, '');
回答2:
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.
回答3:
This is a Javascript solution.
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.
回答4:
Regex is nice, but it's tough to wrangle and you can do the same thing with simpler 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:
var foo = "hello, world\n";
var bar = (foo.indexOf("\n") != -1) ? foo.substring(0, foo.indexOf("\n")) : foo;
来源:https://stackoverflow.com/questions/34214180/how-to-remove-the-line-break-at-the-end-of-a-string