Range of Characters and More Regular Expressions in JavaScript
Welcome to the second part of a five-part series on regular expressions in JavaScript. In the first part we explained why you would want to be familiar with regular expressions and began describing them. In this part we'll pick up where we left off, covering special characters, combining with other characters, character classes, and more.
Range of Characters and More Regular Expressions in JavaScript (Page 1 of 4 )
The m Flag
This flag indicates whether or not to search in the available string across multiple lines.
Note: the g and m flags are not used in as straightforward a manner as it appears. We shall see how to use these two flags after we have learned other things concerning JavaScript regexps.
First Half followed by Second Half of RegExp
Consider the following:
var availableString = “JackSprat is part of a sentence”;
You may be interested in a case where you are looking for the word “Jack” followed (immediately) by the word “Sprat.” The notation for this is:
x(?=y)
meaning, match x only if x is followed (immediately) by y. In our case, x is “Jack” and y is “Sprat.” In our case the test() function should not match (look for) “Jack Sprat,” where there is a space between “Jack” and “Sprat.” It should also not match, for example, “Jack with Sprat,” where there is a word with two spaces between “Jack” and “Sprat.” A match should only be produced if the word “Jack” is immediately followed by “Sprat.” The literal text expression for our regexp is:
/Jack(?=Sprat)/
In our program we can have,
var re = /Jack(?=Sprat)/;
With the above variables, the following expression will return true in a conditional (if statement).
re.test(availableString)
The notation for the opposite effect to x(?=y) is:
x(?!y)
This means that you should match x only if x is not followed (immediately) by y. So if we have
var availableString = “Jack Sprat is part of a sentence”;
var re = /Jack(?!=Sprat)/;
With the above variables, the following expression will return true (produce a match) in a conditional (if statement).
re.test(availableString)
Note the space between “Jack” and “Sprat” in the available string. The match occurs because “Jack” is not followed by “Sprat;” it is followed by a space.