javascript - Why is this regular expression so slow? -
i trying trim leading , trailing whitespace , newlines string. newlines written \n
(two separate characters, slash , n
). in other words, string literal, not cr lf special character.
for example, this:
\n \nright after valid newline:\nand here second line. \n
should become this:
right after valid newline:\nand here second line.
i came solution:
text = text .replace(/^(\s*(\\n)*)*/, '') // beginning .replace(/(\s*(\\n)*)*$/, '') // end
these patterns match fine according regexpal.
however, second pattern (matching end of string) takes long time — 32 seconds in chrome on string couple of paragraphs , few trailing spaces. first pattern quite fast (milliseconds) on same string.
why slow? there better way go this?
the reason takes long because have *
quantifying 2 more *
a explanation can found in php manual, don't think javascript supports once-only subpatterns.
i suggest regex instead:
text = text.replace(/^(?:\s|\\n)+|(?:\s|\\n)+$/g,"");
Comments
Post a Comment