HTML and CSS Reference
In-Depth Information
where results is an array containing each matched substring. For example, the fol-
lowing set of commands extracts the individual words from the text string, placing each
word in the words array:
var regx = /\b\w+\b/g;
var words = “Audio Studio Products”.match(regx);
Similar to the match() method is the split() method, which breaks a text string into
substrings at each location where a pattern match is found, placing the substrings into an
array. The following code shows how to split a text string at each word boundary fol-
lowed by one or more white space characters:
The global modifier
must be set to locate all
matches in the text string.
Without the g modifier,
only the first match is
returned.
var regx = /\b\s*/g;
var words = “ Audio Studio Products”.split(regx);
In this example, each element in the words array contains a word from the sample text
string.
Besides pattern matching and extracting substrings, regular expressions can also be
used to replace text. The syntax of the replace() method is
string .replace( re,newsubstr )
where string is a text string containing text to be replaced, re is a regular expression
defining the pattern of a substring, and newsubstr is the replacement substring. The fol-
lowing code shows how to apply the replace() method to change a text string:
var oldtext = “<h1>Audio Studio Products</h1>”;
var regx = /h1/g;
var newtext = oldtext.replace(regx,”h2”);
In this code, the regular expression matches all of the occurrences of the h1 substring in
the sample text string. When the replace() method is applied to the oldtext variable,
it replaces all occurrences of h1 with h2 . The result is the newtext variable that contains
the text string <h2>Audio Studio Products</h2> . If you neglect to include the g modifier,
only the first occurrence of the substring is replaced.
Figure H-6 summarizes the methods associated with the regular expression object.
Search WWH ::




Custom Search