How do I modify my Javascript Regular expression to return the string: """Collawan Annals of Plastic Surger Jan 1999 vol 42 pg 21 26."""?
How do I properly escape a double quote in a regexp range?
(attempt in Firebug):
&g开发者_如何学运维t;>> var input="Collawn \"Annals of Plastic Surgery\" Jan 1999 vol 42 pg 21 26"
>>> input.replace(/[\.,:\[\]-]/g, ' ');
"Collawn "Annals of Plastic Surgery" Jan 1999 vol 42 pg 21 26"
>>> input.replace(/[\.,:\[\]-\"]/g, ' ');
SyntaxError: invalid range in character class { message="invalid range in character class", more...}
The problem is not the "
but the -
- if you want it to mean a literal dash, you need to put it at the start or the end of the character class:
input.replace(/[.,:\[\]"-]/g, ' ');
Otherwise A-Z
means "any character from A to Z", and your regex contained the equivalent of Z-A
which is an invalid range ([-"
would be ASCII 91 to 34).
The problem here is that \]-\"
describes a character range from ]
(U+005D) to "
(U+0022) that is an illegal range as start > end.
Escape the -
too or put it at the start or end of the character class:
/[\.,:\[\]\-\"]/g
By the way, you only need to escape ]
, and \
, and, depending on the position, also -
and ^
inside a character class, so:
/[.,:[\]\-"]/g
精彩评论