Hi,
May I know the reason of getting the output of the following code as: 1,10,10? Why not it is as: 10, 10?
<script type="text/javascript">
var str="1, 100 or 1000?";
var patt1=/10?/g;
document.write(str.match(patt1));
</script>
Hi,
May I know the reason of getting the output of the following code as: 1,10,10? Why not it is as: 10, 10?
<script type="text/javascript">
var str="1, 100 or 1000?";
var patt1=/10?/g;
document.write(str.match(patt1));
</script>
Because the ?
is a special character in regex, it's an operator makes the single item before it optional. Thus, /10?/
matches a 1 optionally followed by a 0. Hence why it can match just 1
, or the 10
in 100, or the 10
in 1000.
this is a handy cheat sheet for reg expressions.
the bit that you need is in the middle:
you can see the different effects these have, using your code, here
It looks like you may be confusing the precedence
/10?/
This applies ?
only to 0
. If you want 10
to be modified with ?
, then you'd have to group it:
/(10)?/
Or, if you don't need to capture:
/(?:10)?/
Similarly,
/ab+/
Matches abbbbbb
. If you want to match ababab
, then you'd have to write:
/(?:ab)+/
? is a meta-character meaning zero-or-more matches.
To match '?', escape.
var pat = /10\?/g;