admin管理员组

文章数量:1337726

In the popup window, selText does have the value "great," but the length is always undefined. Something related with the encoding of the string?

var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);

In the popup window, selText does have the value "great," but the length is always undefined. Something related with the encoding of the string?

var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);
Share Improve this question edited Mar 21 at 22:00 TylerH 21.1k78 gold badges79 silver badges114 bronze badges asked Feb 12, 2011 at 16:44 pierrotlefoupierrotlefou 40.8k39 gold badges139 silver badges175 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 32

Because you're getting a DOM selection object instead of a String. To get the text, call toString().

var selText = document.getSelection().toString();

The reason the string successfully shows up in the alert, is that the concatenation causes an implicit toString() to occur.

The MDN documentation states.

In the above example, selObj is automatically "converted" when passed to window.alert. However, to use a JavaScript String property or method such as length or substr, you must manually call the toString method.
-- https://developer.mozilla/en/window.getSelection

It's suggesting you call document.getSelection().ToString().length;

Deprecated method document.getSelection() Try use window.getSelection().

var selText = window.getSelection().toString();
        if(selText)
        {
            alert( "selected ->" + selText + " len is " + (selText.length - 1));
        }

本文标签: javascriptWhy does stringlength return undefinedStack Overflow