Form Validation with JavaScript Regular Expressions (Part 1) - Using RegExp
(Page 3 of 5 )
When making use of the constructor RegExp object, the extremely basic example above can be expressed using the following syntax:
var myRegxp = new RegExp("www");
In a very similar manner, you just use the new keyword in conjunction with the RegExp object and substitute the forward slashes for parentheses and double quotes. To use one of the flags, just add the flag inside another set of double quotes and separate with a comma:
var myRegxp = new RegExp("www", "i");
It is also possible to denote repetition of specified characters too; you can use the asterisk symbol after a particular character to specify zero or more times, or the plus symbol to specify one or more:
var myRegxp = /w*/;
document.write(myRegxp.test("test"))
or
var myRegxp = /w+/;
document.write(myRegxp.test("test"))
The first of these examples will produce true, whereas the second will produce false.
You can also use the question mark to state that something should appear zero or one time, and you can use braces to state exactly how many times something should occur:
var myRegxp = /w{3}/;
document.write(myRegxp.test("www"))
which, of course, outputs true. You can also use a comma to separate values to indicate a minimum and maximum range of repetition. Note however that the following code still outputs true:
var myRegxp = /w{3}/;
document.write(myRegxp.test("wwww"))
because there is a string of three w's contained within the string of four w's. This will be examined and overcome in part two.
Next: Other characters >>
More JavaScript Articles
More By Dan Wellman