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);
A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
The length property returns the length of a string. The length property of an empty string is 0.
The Array. find() method returns an undefined value if the condition implemented in the callback function is never satisfied or you haven't returned a value from the callback function. To solve this, use a type guard to check if find returned a value before accessing properties or methods.
Java String length method() The Java String class contains a length() method that returns the total number of characters a given String contains. This value includes all blanks, spaces, and other special characters. Every character in the String is counted.
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.org/en/window.getSelection
It's suggesting you call document.getSelection().ToString().length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With