10.07.2015 Views

regex

regex

regex

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

112As you may know an object can contain methods. Remember that everything in JavaScript isan object. Even a literal string specified with double quotes. In this case, JavaScript has alreadyprovided such a method (called match) to execute a regular expression match:“clockwork“.match(/o/g) ......... Regex match - returns array: [“o”, “o”].“clockwork”.toUpperCase()....... Returns “CLOCKWORK“.“clockwork”.charAt(5) ........... Returns “w” because index counting starts from 0.“clockwork”.length .............. Returns 9 but this is not an object method,this is a member variable or object property.There are a few other methods. In the context of this section we are only interested in themethod called match (also known as object’s member function). The example above shows thatmatch is not a unique method of the string’s object. And it also shows that it is possible to accessit directly from the string definition.As you can see we can call all these functions directly after the closing double quote by accessingthe string’s member function with the dot operator. This can be done without having tostore the string within a unique variable first, but by calling it directly on the value itself.By the way, doing it this way still creates a variable in memory and the value “clockwork” is assignedto it. It’s just we won’t have a name handle to refer to it once the code is finished executing.Sometimes this makes the code cleaner and easier to read.You see, JavaScript already has a number of member functions to help us work with strings.The function match is not the only one, but that is the one we need in order to execute a regularexpression pattern match.Remember that this is rather a less common way to execute a command on a string. This is becausewe are defining the string “clockwork” on the fly and simultaneously accessing its memberfunction match. But the exact same thing could be done using the following statements:var text = “clockwork”;var result = text.match(/o/g);The difference is that here we first stored the string “clockwork” in a variable and only thencalled the function match. But sometimes it is not necessary to do it this way. The choice belongsto the programmer and the circumstances in which the code is written.What else can a regular expression match?Besides matching the characters from the alphabet we can also match other entities. For examplespecial characters like #, $, % and others. In addition, regular expressions make it possiblematching character ranges like A-Z or a-z (notice that the letter case matters) and also

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!