Episodes
Saturday Nov 11, 2006
Javascript Regular Expression
Saturday Nov 11, 2006
Saturday Nov 11, 2006
JavaScript supports regular expressions. The constructor for a RegExp object takes one or two arguments. The first (or only) argument is the string describing the pattern to match; if there is a second argument, it is a string specifying additional processing instructions.
The most basic regular expression is a regular string. For instance, to match the word "cat", you can define the regular expression like this:
var reCat = new RegExp("cat");
This regular expression matches only the first occurrence of the word "cat" in a string, and it is case-sensitive. To make the regular expression match all occurrences of "cat", you can add the second argument to the constructor:
var reCat = new RegExp("cat", "g");
In this line, the second argument "g" is short for global, meaning that the entire string is searching for occurrences of "cat" instead of stopping after the first occurrence. If you want to make the pattern case-insensitive, you can add the character "i" to the second argument ("i" is short for insensitive, as in case-insensitive):
var reCat = new RegExp("cat", "gi");
Some regular expression literals use Perl-style syntax:
var reCat = /cat/gi;
Regular expression literals begin with a forward slash, followed by the string pattern, followed by another forward slash. If you want to specify additional processing instructions, such as "g" and "i", these come after the second forward slash (as in the previous example).
Comments (0)
To leave or reply to comments, please download free Podbean or
No Comments
To leave or reply to comments,
please download free Podbean App.