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?
The reason it takes so long is because you have a * quantifying two more *
A good explanation can be found in the PHP manual, but I don't think JavaScript supports once-only subpatterns.
I would suggest this regex instead:
text = text.replace(/^(?:\s|\\n)+|(?:\s|\\n)+$/g,"");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With