1

I am trying to grab user selected text in a HTML document using javascript. I am using the following code to do it:

function getSelectedText() {
var txt = '';

if (window.getSelection) {
    txt = window.getSelection();
} else if (document.getSelection) {
    txt = document.getSelection();
} else if (document.selection) {
    txt = document.selection.createRange().text;
}

return txt.toString();
}

When I select a word with a leading space, it gets ignore in Firefox. For example, if my text is "Selection example| to| demo space issue" and I make the selection represented by |, which is actually " to" in this case, Firefox ignores the leading space and returns just "to". IE and Chrome does not seem to have this problem and work just fine.

I am trying to surround the selection with a html tag like bold or span which is creating a problem when the leading space is removed.

How to fix this issue?

dev_musings
  • 1,161
  • 1
  • 10
  • 17
  • I don't get the same issue. Firefox will return the leading space in my tests. – John Giotta Mar 02 '11 at 19:07
  • I just restarted my Firefox due to some software update and miraculously, I don't see this issue anymore. Is this a joke? I was stuck with this problem for about an hour. – dev_musings Mar 02 '11 at 19:10
  • @John Giotta I see this problem now in IE6. Firefox somehow seemed to work fine for me too after I restarted. But IE6 is stripping off the leading space. Can you see that? – dev_musings Mar 02 '11 at 19:26

0 Answers0