1.21 gigawatts
1.21 gigawatts

Reputation: 17870

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;

Upvotes: 2

Views: 9402

Answers (5)

Avetik Nersisyan
Avetik Nersisyan

Reputation: 354

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

Upvotes: 0

Barmar
Barmar

Reputation: 782498

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.

Upvotes: 1

jered
jered

Reputation: 11591

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;

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075567

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

Upvotes: 15

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23873

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.

Upvotes: 3

Related Questions