I am trying to extract a number from a string. The number might be zero. Numbers appear like this: ‘+123’, ‘-8’ or ‘0’.
alert( '+123'.match(/[-?|+?]\d+/) );
alerts +123
alert( '-8'.match(/[-?|+?]\d+/) );
alerts -8
alert( '0'.match(/[-?|+?]\d+/) );
alerts null // why oh why?
How do I get ‘0’.match(/[-?|+?]\d+/) to return 0 instead of null?
The pattern
will match exactly one
-,+,|or a?. What you want iswhich will match a
-or a+one or zero times.This will allow numbers like ‘123’ to pass as well. If you require the + sign, use this: