android - How to get Surrounding word in javascript or jquery? -


i working webview , loading html pages in webview here got stuck somewhere, want use javascript.here. explaing need below: having html data this-

"my selected word "widget". i'd know if selection after "red" or "blue". possible? i've been scouring internet advice, , i'm having trouble finding answer"

so suppose above text selected text " selection after"(which shown bold) need previous words before word , words after word in line only. suppose select in line 2 need previous word in line before word , words after selected word in line , in case if selected word in starting of line return previous word null , remaining word after selected word up-to end of line last word vice versa

please tell how achieve using javascript?

i created solution in jsfiddle @ selecting text before , after word

first created paragraph hold text selected

<p id="yourtextcontainer">lorem ipsum data sid amet</p> 

then, in javascript, split paragraph spans, placing index of each word in name attribute. then, when word clicked used index return words before, , words after.

    var textindex; var textbefore; var textafter;  $(document).ready(function(){ var words=$("#yourtextcontainer").text().split(' '); $("#yourtextcontainer").html("");  $.each(words, function(i,val){ //wrap each word in span tag  $('<span name="'+ i+'"+ />').text(val +" ").appendto("#yourtextcontainer");  });  $("#yourtextcontainer span").live("click",function(event){event.stoppropagation();                                                           $("#yourtextcontainer span").css("background-color","white"); $(this).css("background-color","blue");  //gets text of clicked span tag var textselected = $(this).text(); textindex = $(this).attr("name");                                                               alert("you selected "+textselected+" index " + textindex); textbefore= ""; textafter = "";                                                                $("span").each(function (index) {           // alert("looping index " + index);          if (index<(textindex))              textbefore = textbefore + $(this).text() + " ";          if (index>(textindex))              textafter = textafter + $(this).text() + " ";          });      alert("text before "+textbefore );      alert("text after "+textafter );                                                      }); }); 

for example, if click on "ipsum", js alerts, "lorem" text before, , "data sid amet" text after "ipsum".

hope helps! can run fiddle see mean.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -