0

is it possible I could use charAt function within function get selection as below?

getSelected function () {
   var userSelection;
   if (window.getSelection) {
      userSelection = window.getSelection ();
   } else if (document.selection) {
       userSelection = document.selection.createRange ();
   }
   userSelection return;
}

eg : i have a whole text welcome to stack over flow, then the selected text is stack. can i make a function to get specified position with charAt when user select the text and system will compare it with all the text,if system found the same text, system will return the position??

because in my knowledge charAt function can be used to determine the specific position of the string .. http://help.dottoro.com/ljetnrhv.php#charAt

user495688
  • 973
  • 2
  • 15
  • 25

1 Answers1

1

not directly, because both methods return an object rather than string. To use charAt you need to obtain the string value of selection, along the lines of

function getSelectionText() {
   if (window.getSelection)
      return window.getSelection().toString();
   if (document.selection)
       return document.selection.createRange().text;
   return null;
}

alert(getSelectionText().charAt(2)); // 3rd selected char

To find a position of a string inside another string use indexOf. Finding a position of the selection on a page is far more complicated because you need to take html structure into account. Start here and here to find out more.

user187291
  • 53,363
  • 19
  • 95
  • 127
  • can i get specific position if i compare the value of selectedtext with all of text?? – user495688 Dec 09 '10 at 06:02
  • i already use indexOf but return value of the position isn't specified if there's the sama word in the sentence/paragraph. – user495688 Dec 09 '10 at 06:38
  • i can get specific position of text in the sentences,then i can get the right word before and word after selected text..because during this time i can't handle if there are some word with the same content in the sentece like this foo doo lala doo, i mean if user select the 1st word "doo" system get the next word "lala","doo" and the previous word "foo", but if user select the 2nd word "doo", system get the next word empty and the previous word "foo","doo","lala". are u understand with my question or u still confuse with my question? – user495688 Dec 09 '10 at 07:04
  • yes u are right..but when i tried to implement the answer in my code,it's not solve my problem about the word with the same content.. – user495688 Dec 10 '10 at 07:10