Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using window.getSelection to get a string

Tags:

javascript

I'm trying to use window.getSelection to get a string but it's returning an object.

var text = '';
text = document.getSelection();
alert(typeof(text)); //object
like image 996
Dzung Nguyen Avatar asked Dec 03 '25 11:12

Dzung Nguyen


2 Answers

.getSelection() returns a DOMSelection object. The DOMSelection class contains a .toString() method to turn it into a string.

So

var str = window.getSelection().toString();
alert(typeof(str));  // string.
like image 77
kennytm Avatar answered Dec 05 '25 00:12

kennytm


getSelection returns a Selection object. You can get the selected text by calling its toString method.

like image 29
T.J. Crowder Avatar answered Dec 04 '25 23:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!