1

i am trying to find text index using javascript/jquery, but i am not get the exact solution for it.

Consider the text is like this ...

 Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.Hi all. hello world. Hi all. Hello world.

How can i get the exact position of selected 'Hello' word on any line? I tried indexOf, but it is giving me first hello text index. Please any one suggest solution for this.

Thanks in advance.

Sujit
  • 610
  • 7
  • 26

3 Answers3

1

You might want to check this out http://help.dottoro.com/ljkstboe.php

$(document).mouseup(function(){
    selection = window.getSelection();
    index = selection.anchorOffset;
    console.log(index);
});

demo: http://slackware.koding.com/getSelDemo.html

Slackware
  • 960
  • 1
  • 13
  • 29
  • 1
    This is pretty cool. I think I'm gonna start looking into all the fields and functions accessible from window. – Vinay Jan 04 '13 at 05:49
  • This is my question http://stackoverflow.com/questions/14153630/selected-text-editing – Sujit Jan 04 '13 at 14:50
0

try this

var foo="yourstring";
var pos = foo.indexOf("Hello");
while(pos > -1) {
   document.write(pos + "<br />");
   pos = foo.indexOf("Hello", pos+1);
}

here is the fiddle

bipen
  • 36,319
  • 9
  • 49
  • 62
  • 1
    This solution only provides the indexes of all of the "hello" words. What the OP wants is to know the index of the selection – Slackware Jan 04 '13 at 06:01
  • here is my question http://stackoverflow.com/questions/14153630/selected-text-editing – Sujit Jan 04 '13 at 08:33
0

I am not sure why indexOf is not working for you. Same is working for me. Please check the below fiddle.

[HTML]

 <p id="demo">Click the button to locate where in the string a specifed value occurs.     </p>

 <input type="button" id="btn" value="click"/>

[Script]

$('#btn').click(function(){

 var str="Hello world, hello to the universe.";
 var n=str.indexOf("hello");
  alert(n)
});

Demo

RGR
  • 1,521
  • 2
  • 22
  • 36
  • 3
    This is somethign the OP has already tried. He wants to know the postion of a selected text. indexOF works for him but gives the first ocurrence in the string. – Ravi Y Jan 04 '13 at 05:52
  • here is my question http://stackoverflow.com/questions/14153630/selected-text-editing – Sujit Jan 04 '13 at 08:32