Java Reference
In-Depth Information
myText = myText.replace(myRegExp,'“');
textAreaControl.value = myText;
}
The function's parameter is the textarea object defi ned further down the page — this is the text area
in which you want to replace the single quotes. You can see how the textarea object was passed in the
button's tag defi nition.
<input type=”button” value=”Replace Single Quotes” name=”buttonSplit”
onclick=”replaceQuote(document.form1.textarea1)”>
In the onclick event handler, you call replaceQuote() and pass document.form1.textarea1 as the
parameter — that is the textarea object.
Returning to the function, you get the value of the textarea on the fi rst line and place it in the variable
myText . Then you defi ne your regular expression (as discussed previously), which matches any non-
word boundary followed by a single quote or any single quote followed by a non-word boundary. For
example, 'H will match, as will H' , but O'R won't, because the quote is between two word boundaries.
Don't forget that a word boundary is the position between the start or end of a word and a non-word
character, such as a space or punctuation mark.
In the function's fi nal two lines, you fi rst use the replace() method to do the character pattern search
and replace, and fi nally you set the textarea object's value to the changed string.
The search() Method
The search() method enables you to search a string for a pattern of characters. If the pattern is found,
the character position at which it was found is returned, otherwise -1 is returned. The method takes
only one parameter, the RegExp object you have created.
Although for basic searches the indexOf() method is fi ne, if you want more complex searches, such as
a search for a pattern of any digits or one in which a word must be in between a certain boundary, then
search() provides a much more powerful and fl exible, but sometimes more complex, approach.
In the following example, you want to fi nd out if the word Java is contained within the string.
However, you want to look just for Java as a whole word, not part of another word such as
JavaScript.
var myString = “Beginning JavaScript, Beginning Java 2, Professional JavaScript”;
var myRegExp = /\bJava\b/i;
alert(myString.search(myRegExp));
First, you have defi ned your string, and then you've created your regular expression. You want to fi nd
the character pattern Java when it's on its own between two word boundaries. You've made your
search case-insensitive by adding the i after the regular expression. Note that with the search()
method, the g for global is not relevant, and its use has no effect.
On the fi nal line, you output the position at which the search has located the pattern, in this case 32.
Search WWH ::




Custom Search