I am trying to trim leading and trailing whitespace and newlines from a string. The newlines are written as \n
(two separate characters, slash and n
). In other words, it is a string literal, not a CR LF special character.
For example, this:
\n \nRight after this is a perfectly valid newline:\nAnd here is the second line. \n
Should become this:
Right after this is a perfectly valid newline:\nAnd here is the second line.
I came up with this solution:
text = text
.replace(/^(\s*(\\n)*)*/, '') // Beginning
.replace(/(\s*(\\n)*)*$/, '') // End
These patterns match just fine according to RegexPal.
However, the second pattern (matching the end of the string) takes a very long time — about 32 seconds in Chrome on a string with only a couple of paragraphs and a few trailing spaces. The first pattern is quite fast (milliseconds) on the same string.
Here is a CodePen to demonstrate it.
Why is it so slow? Is there a better way to go about this?