regular expression in javascript
We have two ways to construct a regular expression in javascript1. reg = /ab+c/; using expression literal when you want the req to be compiled at evaluate time
2. re g = new RegExp("ab+c"); Using the constructor when you want to to compile the reg at compilation times. Using the constructor function when you know the regular expression pattern will be changing.
Using Simple Patterns
Simple patterns are used when we want to find a direct match. Let say we want to find a pattersn /abc/, thus it will be only matched when the string contains the 'abc' in the same order. for example we want to find the patterns /abc/ in string 'we want to find abc', this will match the patterns.
Using Special Characters
Special character is used when we want to find something more than a direct match. Let say we want to find something like /go*d/. This pattern means that it will match any combination that start with 'g' and follow by zero or more occurrences of 'o' then followed by 'd'. For example the pattern /go*d/ will match in any string 'I want to buy som goods and god book'
$ = Matche the end of input. eg. /a$/ will match 'nruna' but not 'arun'.
+ = Matches the preceding character 1 or more times. eg. /a+/ will match 'aruna' or 'arunaaaaa'.
? = Matches the preceding character 0 or 1 time
. eg. /e?le?/
will matche the 'el' in "angel" and the 'le' in "angle.". = Matches any single character but not the new line character. eg. /.l/ will match something in string 'long live, long day' but not 'long'.
No comments:
Post a Comment