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
}
Try:
if(x.lastIndexOf("\n")>0) {
return x.substring(0, x.lastIndexOf("\n"));
} else {
return x;
}
x
contains one single line (may not be a problem depending on the exact need).
Nov 30, 2012 at 14:58
You can use a regular expression (to be tuned depending on what you mean by "last line"):
return x.replace(/\r?\n?[^\r\n]*$/, "");
A regex will do it. Here's the simplest one:
string.replace(/\n.*$/, '')
\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
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!
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()
<br>
?