Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why string.length return undefined?

Tags:

javascript

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);
like image 755
pierrotlefou Avatar asked Feb 12 '11 16:02

pierrotlefou


People also ask

Why is return undefined?

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 .

Which property returns the length of a string?

The length property returns the length of a string. The length property of an empty string is 0.

Why is Array find returning undefined?

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.

How do you determine the length of a string?

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.


2 Answers

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.

like image 58
user113716 Avatar answered Sep 24 '22 19:09

user113716


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;

like image 20
John K Avatar answered Sep 23 '22 19:09

John K