18

How do I remove the last line "\n" from a string, if I dont know how big the string will be?

var tempHTML = content.document.body.innerHTML;
var HTMLWithoutLastLine = RemoveLastLine(tempHTML);

function RemoveLastLine(tempHTML)
{
   // code
} 
4
  • what is last line ?? is it constant or can vary ...
    – Scorpio
    Nov 30, 2012 at 14:45
  • After the last new line or the last <br>? Nov 30, 2012 at 14:45
  • Assuming you have \n in the string, then string.substring(0,string.lastIndexOf("\n")); would perhaps be what you want
    – mplungjan
    Nov 30, 2012 at 14:47
  • @insertusernamehere yes, everything that comes after the last \n or new line needs to be removed. Nov 30, 2012 at 14:47

5 Answers 5

27

Try:

if(x.lastIndexOf("\n")>0) {
    return x.substring(0, x.lastIndexOf("\n"));
} else {
    return x;
}
3
  • 1
    Doesn't work if x contains one single line (may not be a problem depending on the exact need). Nov 30, 2012 at 14:58
  • @JulienRoyer You are right. I updated my answer. Btw +1 for your answer.
    – rekire
    Nov 30, 2012 at 16:57
  • Note that with this answer you need to be absolutely certain that there actually is a trailing space or else you will end up deleting the last line of the text.
    – Mike
    Aug 2, 2016 at 18:00
10

You can use a regular expression (to be tuned depending on what you mean by "last line"):

return x.replace(/\r?\n?[^\r\n]*$/, "");
4

A regex will do it. Here's the simplest one:

string.replace(/\n.*$/, '')

See regex101 for how it works

\n matches the last line break in the string

.* matches any character, between zero and unlimited times (except for line terminators). So this works whether or not there is content on the last line

$ to match the end of the string

1

In your specific case the function could indeed look like:

function(s){
  return i = s.lastIndexOf("\n")
    , s.substring(0, i)
}

Though probably you dont want to have spaces at the end either; in this case a simple replace might work well:

s.replace(/s+$/, '')

Keep in mind however that new versions of Javascript (ES6+) offer shorthand ways of doing this with built-in prototype functions (trim, trimLeft, trimRight)

s.trimRight()

Cheers!

0

Make the string to an array and pop away the last line.

The value from the pop is not used, so it go to the void.

function RemoveLastLine(x) {
    x = x.split('\n');
    x.pop();
    return x.join('\n')
}

Make it back to a string with Array.join()

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.