15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

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 16 ✦ String and Number Objects (Chapters 34 and 35)<br />

Figure 16-2: Using the default replacement regular expression<br />

You could modify the listing so that it actually replaces text in the HTML paragraph<br />

for IE4+ and NN6. The steps include wrapping the paragraph in its own element<br />

(for example, a SPAN), and invoking the replace() method on the<br />

innerHTML of that element. Assign the results to the innerHTML property of that<br />

element to complete the job.<br />

Listing 34-4: Lab for string.replace() and string.search()<br />

<br />

<br />

Regular Expression Replace and Search<br />

<br />

var mainString = “To be, or not to be: that is the question:\n”<br />

mainString += “Whether \’tis nobler in the mind to suffer\n”<br />

mainString += “The slings and arrows of outrageous fortune,\n”<br />

mainString += “Or to take arms against a sea of troubles,\n”<br />

mainString += “And by opposing end them.”<br />

function doReplace(form) {<br />

var replaceStr = form.replaceEntry.value<br />

var delim = (form.caseSens.checked) ? “/g” : “/gi”<br />

var regexp = eval(“/” + form.regexp.value + delim)<br />

form.result.value = mainString.replace(regexp, replaceStr)<br />

}<br />

Continued<br />

477<br />

stringObject.replace()

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

Saved successfully!

Ooh no, something went wrong!