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
3 Answers
Reset to default 32Because 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
版权声明:本文标题:javascript - Why does string.length return undefined? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743494495a2494359.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论