The RegExp
object is the base object used in the JavaScript's implementation of regular expressions, more specifically of the Perl-compatible regular expressions (with some differences). This object differs from the literal version of regular expressions in two points: it accepts user input and its special modifiers are double-escaped. The first point is very useful, because we can dynamically build a regular expression using the user input retrieved for example from a form field. An example of this feature is the following:
var userInput = document.getElementById('query').value; var pattern = new RegExp(userInput, 'g'); var content = element.innerHTML; if(pattern.test(content)) { alert('Found'); }
The general syntax of this object constructor is:
RegExp(pattern, flags)
All the flags used in the literal version also apply here.
The above example uses the test()
function to check whether an element's HTML content contains a given pattern. Another example is mostly used by many JavaScript libraries to test whether an element contains a given attribute, for example a CSS class:
HTMLElement.prototype.hasClass = function(name) { var cssClass = this.className; var pattern = new RegExp('^\\b' + name + '\\b$'); if(pattern.test(cssClass)) { return true; } else { return false; } };
Note how the special word boundary modifier (\b
) has been written in the code above:
\\b
with a double backslash. Note also how the function parameter has been inserted into the RegExp
constructor using the +
operator:
'^\\b' + name + '\\b$'
These are the main differences between the RegExp
constructor and the literal version of JavaScript regular expressions.