Sujit
Sujit

Reputation: 658

Selected text index

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.

Upvotes: 1

Views: 129

Answers (3)

Slackware
Slackware

Reputation: 1000

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

Upvotes: 1

RGR
RGR

Reputation: 1571

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

Upvotes: 0

bipen
bipen

Reputation: 36531

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

Upvotes: 0

Related Questions