String manipulation and regular expressions, part two
Notes from June 10, 2005 class
Within this string:
var myString = "JavaScript, VBScript, and Perl";
how can we match both JavaScript and VBScript using one RegExp?
We can use parentheses to group parts of a regular expression. That lets us treat a number of expressions as a single group.
We can use | to mean or, thus looking for something that matches either "Java" or VB":
var myRegExp= /\b(VB|Java)Script\b/gi;
// starting and ending with a "/" makes a regular expression
// \b means a word boundary
// (VB|Java) gets either "VB" or "Java"
// /g makes it match all instances, not just the first
// /i makes it case-insensitivemyString=myString.replace(myRegExp, "zzzz");
alert(myString)Here's the script in action.
The match() method
The match() method returns an array, with each element containing the text of a match that was made.
var myString= "The years were 1999, 2000, and 2001 but not Year2020Madness";
Let's extract the years from that string, and put each into an alert box.
var myYears = /\b\d{4}\b/g;
/* Explanations about what all that alphabet soup is for:
\b for word boundary, so we don't pick up the 2020 in Year2020Madness
\d{4} looks for 4 digits in a row
The g after the closing / makes it a global search
*/var resultsArray = myString.match(myYears);
if (resultsArray)
{var indexCounter;
for (indexCounter = 0; indexCounter < resultsArray.length; indexCounter++)
{alert(resultsArray[indexCounter]);
}
}
Here's the script in action.