Home > Computers & Technology > Software > Software & Web Development
Created on: March 07, 2009 Last Updated: March 11, 2009
JavaScript String Regular Expressions Part 4
Introduction This is the fourth part of my series JavaScript String Regular Expressions. You can actually group bits of a regular expression and do something with it. That is what this part of the series is about.
Groupings We can use parenthesis to group characters in a pattern. Consider the following pattern:
/The (guitarist)/
"guitarist" is in parenthesis. The parentheses form a group, which has the text: "guitarist". Consider the following:
/The (guitarist is good)/
"guitarist is good" is in parenthesis. The parentheses form a group, which has the text: "guitarist is good".
JavaScript treats a group as an entity. A group on its own is not serving any purpose. It becomes important when used in conjunction with other pattern techniques. There is another use, which we shall see below.
The String match() Method The string object has a method called, match(). Ordinarily, this method returns a one element array whose element is the sub string found in the subject; however, if no sub string is found, the return value is null (not an array). Let us demonstrate this before we continue.
<html> <head> </head> <body> <script type="text/javascript"> var arr = "Hello World!".match(/World/) alert(arr); </script> </body> </html>
The above script uses the match method. The subject string is "Hello World!". The regex is /World/. The return value is an array, which is, arr. Matching occurs and "World" from the subject is sent to the array as the only element. The second statement of the script should display all the elements of the array; well there is only one element in the array, so it displays just the one element, which is "World". Everything being equal, the matching method returns a one-element array.
Let us now look at the case where matching does not occur. Remember that matching is case sensitive. So if we use "world" in the pattern, where "W" is in lower case, matching world not occur. Let us try it.
<html> <head> </head> <body> <script type="text/javascript"> var arr = "Hello World!".match(/world/) alert(arr); </script> </body> </html>
Here, matching does not occur, there is no array and the return value of the match method is null. The second statement (alert) displays, null. You should try the above programs.
Note: either the subject or the regex, for the match method can be a variable.
Sub Strings with common Parts Imagine that you have
Below are the top articles rated and ranked by Helium members on:
Grouping in JavaScript string regular expressions
Helium Debate
Cast your vote!
Will Internet Explorer 8 solve Microsoft's Web browser problems?
Click for your side.
Featured Partner
Promoting the health and well-being of Americans through programs and activities.more