kapalkat
kapalkat

Reputation: 406

How to remove only last new line with regular expression in javascript

I have a file like so:

const stringToTest = ' test1\n test2\n test3\n \n \n'

The output I want to get is:

stringTransformed = 'test1\n test2\n test3\n \n'

so in other words I want to get rid of only LAST white space and new line:

' \n'

I have tried following:

stringToTest.replace(/\s+\n$/, '')

but it removes all white spaces and new lines at the end of the file.

I know I can do it with split and join but I would prefer to do it with regular expression as it's much faster and sometimes my strings are really big so I don't want to split them into arrays.

Upvotes: 1

Views: 690

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

Your \s pattern matches any whitespace. If you subtract CR and LF symbols from it, you will only match horizontal whitespaces.

So, you may use

replace(/[^\S\n\r]*\n$/, '')

Or, to also handle CRLF endings:

replace(/[^\S\n\r]*\r?\n$/, '')

Note I changed + to * quantifier to also remove the last line break if there are no horizontal whitespace chars on the line before the last newline.

JS demo:

const stringToTest = ' test1\n test2\n test3\n \n \n';
console.log(stringToTest.replace(/[^\S\n\r]*\n$/, ''));

Upvotes: 2

Related Questions