18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7<br />

Expressions to match leading and trailing white space are very simple thanks to the \s character class<br />

that matches all the white space characters:<br />

var reExtraSpace = /^\s+(.*?)\s+$/;<br />

This regular expression looks for one or more occurrences of white space at the beginning of the string,<br />

followed by any number of additional characters (which are captured in a group), followed by one or<br />

more occurrences of white space at the end of the string. By using this in conjunction with the String<br />

object’s replace() method and backreferences, you can define your own trim() method:<br />

String.prototype.trim = function () {<br />

var reExtraSpace = /^\s+(.*?)\s+$/;<br />

return this.replace(reExtraSpace, “$1”);<br />

};<br />

With this method, you can create trimmed versions of strings very easily:<br />

var sTest = “ this is a test “;<br />

alert(“[“ + sTest + “]”); //outputs “ [ this is a test ] “<br />

alert(“[“ + sTest.trim() + “]”); //outputs “ [this is a test]”<br />

Backreferences<br />

So what do you do with groups after the expression has been evaluated? Each group is stored in a special<br />

location for later use. These special values, stored from your groups, are called backreferences.<br />

Backreferences are created and numbered by the order in which opening parenthesis characters are<br />

encountered going from left to right. <strong>For</strong> example, the expression (A?(B? (c?))) creates three backreferences<br />

numbered 1 through 3:<br />

1. (A? (B? (c?)))<br />

2. (B? (c?))<br />

3. (c?)<br />

The backreferences can then be used in a couple of different ways.<br />

First, the values of the backreferences can be obtained from the RegExp constructor itself by using the<br />

test(), match(), or search() methods. <strong>For</strong> example:<br />

var sToMatch = “#123456789”;<br />

var reNumbers = /#(\d+)/;<br />

reNumbers.test(sToMatch);<br />

alert(RegExp.$1); //outputs “123456789”<br />

This example tries to match the pound sign followed by one or more digits. The digits are grouped so<br />

they will be stored. After the test() method is called, all backreferences have been stored on the<br />

RegExp constructor starting with RegExp.$1, which stores the first backreference (it continues with<br />

RegExp.$2 if there is a second, RegExp.$3 if there is a third, and so on). Because the group matches<br />

“123456789”, that is what is stored in RegExp.$1.<br />

206

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

Saved successfully!

Ooh no, something went wrong!