Case and Negation in JavaScript Regular Expressions
Welcome to the third part of a five-part series that examines the use of regular expressions in JavaScript. In this part, we'll look at the effects of case sensitivity, how to use negation, and more.
Case and Negation in JavaScript Regular Expressions - Beginning and Ending a String (Page 3 of 5 )
The aim here is to see how you can match a regexp to the beginning of the available string or the end of the available string, or both the beginning and the end.
The ^ Character for Matching at the Beginning
If you want the matching to occur at the beginning of the available string, start the regexp with the '^' character.
The following code produces a match:
/^one/.test("one and two")
The following code does not produce a match:
/^one/.test("The one I saw")
In the first case the word "one" is at the beginning of the available string. In the second case, the word "one" is not at the beginning of the available string.
At this point, you may ask, "Is '^' not the negation symbol?" Well it is the negation symbol. The problem is to know when to use it. When used inside a class (square brackets), it is the negation symbol; when used at the beginning of a regexp, just after the forward slash, it is the regexp character for matching at the beginning of the available string.
The $ Character for Matching at End
If you want the matching to occur at the end of the available string, start the regexp with the '$' character.
The following code produces a match:
/last$/.test("This is the last")
The following code does not produce a match:
/last$/.test("The last boy")
In the first case the word "last" is at the end of the available string. In the second case, the word "last" is not at the end of the available string.
After the next section, I show you how to match the whole string.