Reputation: 3418
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
}
Upvotes: 21
Views: 27041
Reputation: 2263
I use trimEnd to remove last line of a string:
const text = `test
multiple
lines
`
const lines = text.trimEnd().strip('\n')
Upvotes: 0
Reputation: 208
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()
Upvotes: 0
Reputation: 5243
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
Upvotes: 4
Reputation: 6469
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!
Upvotes: 1
Reputation: 47945
Try:
if(x.lastIndexOf("\n")>0) {
return x.substring(0, x.lastIndexOf("\n"));
} else {
return x;
}
Upvotes: 30
Reputation: 1429
You can use a regular expression (to be tuned depending on what you mean by "last line"):
return x.replace(/\r?\n?[^\r\n]*$/, "");
Upvotes: 10