15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

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.

476<br />

<strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

stringObject.replace()<br />

RegExp Description<br />

man Both case-sensitive and not<br />

man\b Where “man” is at the end of a word<br />

\bman Where “man” is at the start of a word<br />

me*an Where zero or more “e” letters occur between “m” and “a”<br />

.a. Where “a” is surrounded by any one character (including<br />

space)<br />

\sa\s Where “a” is surrounded by a space on both sides<br />

z Where a “z” occurs (none in the default string)<br />

In the scripts for Listing 34-3, if the string.match() method returns null, you<br />

are informed politely, and the count field is emptied.<br />

string.replace(regExpression, replaceString)<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓ ✓ ✓ ✓<br />

Example<br />

The page in Listing 34-4 lets you practice with the string.replace() and<br />

string.search() methods and regular expressions in a friendly environment. The<br />

source text is a five-line excerpt from Hamlet. You can enter the regular expression<br />

to search for, and the replacement text as well. Note that the script completes the<br />

job of creating the regular expression object, so that you can focus on the other<br />

special characters used to define the matching string. All replacement activities act<br />

globally, because the g parameter is automatically appended to any expression you<br />

enter.<br />

Default values in the fields replace the contraction ‘tis with “it is” after you click<br />

the “Execute replace( )” button (see Figure 16-2). Notice that the backslash character<br />

in front of the apostrophe of ‘tis (in the string assembled in mainString) makes<br />

the apostophe a non-word boundary, and thus allows the \B’t regular expression<br />

to find a match there. As described in the section on the string.search()<br />

method, the button connected to that method returns the offset character number<br />

of the matching string (or -1 if no match occurs).

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

Saved successfully!

Ooh no, something went wrong!