Number of occurences using ?
If a pattern has ? , it means that the character preceding ? has either 0 or 1 occurrence. In other words, the character preceding ? is optional. Let us repeat the above example with ? in place of +..
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Javascript Regular Expression Example 6 Number of occurrences with ? ******************************************************** */ var pattern1=new RegExp("fo?d"); var string1 = new Array(5); string1[0] = "food"; string1[1] = "fod"; string1[2] = "fd"; string1[3] = "foooood"; string1[4] = "fud"; var i; for(i=0; i<=4; i++) { if (pattern1.test(string1[i])) { document.write(string1[i], " -> match found with fo?d ","<br\>"); } else { document.write(string1[i], " -> match not found with fo?d","<br\>"); } } //--> </script> </body> </html> |
Try this Example online
You can try this example online at - here .
This script gives the following output.
food -> match not found with fo?d fod -> match found with fo?d fd -> match found with fo?d foooood -> match not found with fo?d fud -> match not found with fo?d
Can you think of a practical example of the anchor "?". Assume that you want to search for a string which can be singular or plural. So the regular expression RegExp("expressions?") will match the strings "expression" as well as "expressions".