javascript - Why does string.length return undefined? - Stack Overflow

In the popup window, selText does have the value "great," but the length is always undefined.

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));
        }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743494496a4463129.html

相关推荐

  • javascript - Why does string.length return undefined? - Stack Overflow

    In the popup window, selText does have the value "great," but the length is always undefined.

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信