简体   繁体   中英

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

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 . 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]+$/, '');

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.

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.

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;

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" }`;
}

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