RegExp, object of regular expression in JavaScript
The RepExp object is declared with a regular expression and its methods are applied to a content, either to check that the text matches the definition, or to extract parts of the text.
Methods defined in the RepExp object may be involved with the instance or directly with a literal.
The parameter of the contructor is a regular expression mask
The RegExp constructor has two possible parameters, the regular expression in the form of string, and the modifier which is optional.
var x = new RegExp("expression" [, "modifier"])
The modifier is a letter or combination of "i", "g", "m" letters.
The variable x is an instance of RegExp to which may be associated methods, and that can also be a parameter for some String functions.
The object is used by applying its methods to a content
Once the instance of the object created, a method is associated to it, with for parameter the content that you want to parse with the regular expression.
var result = x.test("text");
An object can also be used as a parameter of some methods of the String object, including search, replace, match.
Example:
var s = new String("hello");
var re = new RegExp("(o)+");
document.write(s.search(re));
Returns and displays the number 4, because "o" is in position 4 from zero.
In combination with the object String, it is possible to add functions to this list as we saw with the previous example (search method).
See also
- Regular Expressions in JavaScript.
- Testing regular expression in JavaScript. And other programming languages.