最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using window.getSelection to get a string - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question edited Sep 14, 2011 at 20:33 Alex Turpin 47.8k23 gold badges116 silver badges146 bronze badges asked Mar 10, 2010 at 14:51 Tzu ngTzu ng 9,24414 gold badges68 silver badges106 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

.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.

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

text = document.getSelection()+'';
alert(typeof(text)); // << it returns string
发布评论

评论列表(0)

  1. 暂无评论