0

Look at these two javascript commands:

alert(' test £32 <!-- -->'.replace(/^\s+|[ ><!-]+$/g,''));

alert(' test £32 <!-- -->'.replace(/^\s+|[ <!->]+$/g,''));

The first one operates correctly - it alerts the message "test £32", which is what I would expect. However, the second one produces "test £". Why is this? Why does moving the > within the [] cause it to start stripping numbers?

Benubird
  • 18,551
  • 27
  • 90
  • 141

2 Answers2

0

Moving the - from last place to between ! and > makes a huge difference. Specifically, if - is not the first or last character specified inside the character class then you will have a construct like a-b. The class will then match all characters with code points between those of a and b.

The Unicode code point for ! is U+0021, while the code point for > is U+003E. The intervening range contains a number of characters that include all digits (those have code points from U+0030 to U+0039) -- you can see an exact list here. Therefore the character class ends up matching the digits as well.

To fix the problem, either place the hyphen in the last position inside the character class (as it is in your first example) or else escape it with a backslash to treat it as a literal character:

alert(' test £32 <!-- -->'.replace(/^\s+|[ <!\->]+$/g,''));
Jon
  • 428,835
  • 81
  • 738
  • 806
0

You must escape the - to \- as - builds a range in regex, .

Use

' test £32 <!-- -->'.replace(/^\s+|[ ><!\-]+$/g,'')
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758