Retrieving Selections in Navigator 4.0x
Navigator 4.0x features the
getSelection() method of the
document object. This method returns a string containing the text of the current selection. Its general syntax is:
The following example demonstrates the
The script displays the current selection in a box. At first, it instructs the browser to capture all
mouseup events. As explained in Column 9, Column 10, and Column 11, this is only required for Navigator 4.0x, so a simple object detection routine makes sure the browser is Navigator 4.0x before executing the statement.
The event processing function first assigns the selection's text to a variable named
str. It then assigns that variable to the
value property of the form element, so the selection is displayed in the box. Now go ahead and drag the mouse over some text. If you're using Navigator 4.0x, the selection will immediately display in the box.
if (!document.getSelection) return;
terminates the function if the user is running a browser that doesn't support the
getSelection() method. Therefore, no error is generated on Internet Explorer 4.0x or older browsers.
Notice that the document's layout affects the value returned by the
getSelection() method. For example, this page utilizes a
<BLOCKQUOTE>...</BLOCKQUOTE> pair to indent the content for easier reading. If you select several lines of text, the second (and third, fourth, fifth, etc.) line's text is indented, due to the
<BLOCKQUOTE> definition. In this case, the new line consists of a carriage return (
\r), a line feed (
\n), and five spaces. You can discover what characters make up the new line by displaying the escaped value of the string:
escape() function accepts a string argument and returns the same string with all non-alphanumeric characters translated into their equivalent hexadecimal code.
\r\n combination is platform-dependent, so we'll simply delete the five spaces that follow it. Here's the alternative script:
First we discovered what series of characters was causing trouble, by displaying the value returned by the
escape() function, as explained earlier. We immediately noticed five consecutive non-alphanumeric characters:
%20%20%20%20%20. Therefore, the function unescapes those characters and assigns the value to a variable. A regular expression is then defined as an instance of the
RegExp object. Notice the
"g" argument. It specifies that the string should be matched against the regular expression multiple times if the pattern is found more than once in the string. The final string is displayed after replacing all occurences of five consecutive spaces with an empty string.
Created: January 29, 1998
Revised: January 29, 1998