'Remove last line from string

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
} 


Solution 1:[1]

Try:

if(x.lastIndexOf("\n")>0) {
    return x.substring(0, x.lastIndexOf("\n"));
} else {
    return x;
}

Solution 2:[2]

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

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

Solution 3:[3]

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

Solution 4:[4]

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!

Solution 5:[5]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Marco Roy
Solution 4 Ivo
Solution 5