23.04.2013 Views

javascript

javascript

javascript

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.

CHAPTER 2 ■ TYPE CONVERSION<br />

40<br />

Figure 2–15. Splitting a string into smaller strings with split()<br />

Say the final villain is prefaced by ", and " rather than ", ". That is to say, we want to divvy up a<br />

string based on two dividers, ", " or ", and ". This can’t be done by passing a string divider. Rather,<br />

we’d need to pass in a RegExp literal to match both dividers:<br />

/, (?:and )?/g<br />

Don’t worry, this won’t look like gobbledygook by the end of Chapter 5 (note how you can identify<br />

the dividers in the expression, and we’re using /g again). Try the following sample in Firebug, verifying<br />

your work with Figure 2–16:<br />

var villains = "Green Goblin, Doctor Octopus, Venom, Hobgoblin, and Sandman";<br />

villains.split(/, (?:and )?/g);<br />

// ["Green Goblin", "Doctor Octopus", "Venom", "Hobgoblin", "Sandman"]

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

Saved successfully!

Ooh no, something went wrong!