04.11.2015 Views

javascript

Create successful ePaper yourself

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

Chapter 5: Reference Types<br />

Sequence<br />

Replacement Text<br />

$$ $<br />

$ & The substring matching the entire pattern. Same as RegExp.lastMatch .<br />

$’ The part of the string occurring before the matched substring. Same as RegExp<br />

.leftContext.<br />

$` The part of the string occurring after the matched substring. Same as RegExp<br />

.rightContext.<br />

$n The n th capture, where n is a value 0 – 9. For instance, $1 is the first capture, $2 is<br />

the second, etc. If there is no capture then the empty string is used.<br />

$nn<br />

The nn th capture, where nn is a value 01 – 99. For instance, $01 is the first capture,<br />

$02 is the second, etc. If there is no capture then the empty string is used.<br />

Using these special sequences allows replacement using information about the last match, such as in this<br />

example:<br />

var text = “cat, bat, sat, fat”;<br />

result = text.replace(/(.at)/g, “word ($1)”);<br />

alert(result); //word (cat), word (bat), word (sat), word (fat)<br />

Here, each word ending with “ at ” is replaced with “ word ” followed in parentheses by what it replaces<br />

by using the $1 sequence.<br />

The second argument of replace() may also be a function. When there is a single match, the function<br />

gets passed three arguments: the string match, the position of the match within the string, and the whole<br />

string. When there are multiple capturing groups, each matched string is passed in as an argument, with<br />

the last two arguments being the position of the pattern match in the string and the original string. The<br />

function should return a string indicating what the match should be replaced with. Using a function as<br />

the second argument allows more granular control over replacement text, as in this example:<br />

function htmlEscape(text){<br />

return text.replace(/[ < > ” & ]/g, function(match, pos, originalText){<br />

switch(match){<br />

case “ < ”:<br />

return “ & lt;”;<br />

case “ > ”:<br />

return “ & gt;”;<br />

case “ & ”:<br />

return “ & amp;”;<br />

case “\””:<br />

return “ & quot;”;<br />

}<br />

});<br />

}<br />

alert(htmlEscape(“ < p class=\”greeting\” > Hello world! < /p > ”));<br />

//” & lt;p class= & quot;greeting & quot; & gt;Hello world! & lt;/p & gt”;<br />

139

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

Saved successfully!

Ooh no, something went wrong!