Regular Expression in Javascript - Number of occurences using +
The character + indicates that the we should have one or more occurrences of the character preceding it.
To understand the necessity of the anchor + where we want to write a pattern that will match any string that contains
203
2003
20003
200003
and so on and so forth. In other words there should be one or more than one 0s between 2 and 3. It should however not match 23.Javascript provides anchor + to do this job. The following pattern will do this job
pattern = new RefExp("20+3")
The 0+ in the pattern "20+3" says that we want to match a string that contains 2 followed by ONE or MORE THAN ONE occurrences of 0 followed by 3.
Let us understand with a complete example
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Javascript Regular Expression Example 5 Number of occurrences with + ******************************************************** */ var pattern1=new RegExp("fo+d"); var string1 = new Array(4); string1[0] = "food"; string1[1] = "fod"; string1[2] = "fud"; string1[3] = "foooood"; var i; for(i=0; i<=3; 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 .
It gives the following output
food -> match found with fo+d fod -> match found with fo+d fud -> match not found with fo+d foooood -> match found with fo+d
The pattern fo+d essentially means that there can be one or more number of o's following fo.