0

As an example that we have

Name : Abdul Naeem

if we select the Naeem from above so to get Abdul From it.......

is it possible to get the left side words of the selected words

i tried but i have not found this..... can any body help me out of this problem.

i found some tips where it only get the selected words but i need the words on its left side

Get the Highlighted/Selected text

for example lets consider if an object weighs 30 N. now i want to select the 30, and get the word weighs from it ?? how can i do it in javascript –

Community
  • 1
  • 1
  • I ask all answerers to reread the question. The OP is not trying to find a word before another word in a *string*, but a word (or words, title and question do not match) before the *selected* word, where *selected* is a DOM `Selection` (which is made explicit by the link). – Amadan Nov 11 '14 at 06:57
  • How can you fire onclick event on portions of text of an element? Example-

    Name : Abdul Naeem

    . Onclick will be fired on complete

    not on portion of p. However whatever you want can be achieved if they are in seperate element like--

    Name

    :

    Abdul

    Naeem

    – RahulB Nov 11 '14 at 07:16
  • by the way thanks it is little bit matched with my problem –  Nov 11 '14 at 07:16
  • Are you looking for something like this http://jsfiddle.net/RahulB007/dpej97cn/ – RahulB Nov 11 '14 at 08:16
  • No as example i have alot of Words where i select a word from it so the left side of that word i have selected should be refered if an object weighs 30 N on earth and what will be the weighsonearth? if i select 30 from above where 30 is a word so the left side of it weighs have to be returned where in it's left word may have different length 3 letter or many be infinite –  Nov 11 '14 at 08:27
  • That is what i said above. You want click function on individual words. That way, each word require to be wrapped in a tag to invoke onclick function. That way you need to hardcode for creating/wrapping in tags – RahulB Nov 11 '14 at 08:51

6 Answers6

1

It is nontrivial, mainly because of the hierarchical nature of the document.

A restricted functionality which will get you the previous word as long as it is in the same element, in non-IE browsers:

// get the selection
var sel = window.getSelection();
// get the element in which the selection is made, and the start and end position
var node = sel.anchorNode;
var from = sel.anchorOffset;
// let's see what's before the selection
var textBeforeWord = node.textContent.substring(0, from);
var match = textBeforeWord.match(/(\w+)\s+/);
var previousWord = match[1];

This gets much more complicated when you consider the possibility that a word could be the first thing in its element, or that a selection might be across elements, when you would need to navigate the DOM hierarchy to hunt the previous element. It is also complicated by the fact that you would need to do it twice, completely differently (since IE's API is totally different).

EDIT In case of a <textarea> element, it gets much simpler, as you don't need to worry about the selection spilling over the element. For IE you will have to do some gymnastics, since it does not support selectionStart, as described here.

var node = document.getElementById('mytextarea');
var from = node.selectionStart;
var textBeforeWord = node.textContent.substring(0, from);
// the rest is the same as above
Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • If you needed `textarea` selection, it would have been nice to write it in the question. I will expand my answer. – Amadan Nov 11 '14 at 07:01
  • Sorry about that but now you know please Help me out Thanks –  Nov 11 '14 at 07:06
0

Let assume these first :

all text in textbox = Abdul Naeem

currently selected text = ul Naeem

currently unselected text = Ab

Now, from your question, you only want to get the unselected text right, which is in this case is Ab? Then make three variable like this :

var allText = ... // get it from your textbox value
var selectedText = ... // try to get it using your link location
var unselectedText = allText.replace(selectedText, '');

Then you get the unselectedText. Thanks & Regards.

the.wizard
  • 1,079
  • 1
  • 9
  • 25
0

note just tested it in **CHROME, it will display all words to left to "SELECTED" Word

You need to modify it a little bit according to your need, just try

//console.log(window.getSelection().focusNode.data);

var textSelected = window.getSelection().toString();

var fulltext = window.getSelection().focusNode.data;

console.log(fulltext.substr(0,fulltext.length-textSelected.length));
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
0

I found the question quite interesting and thus I tried to do it with the help of Javascript. I wouldnt call it a good code but it does what you require Abdul. Providing you the whole code along with html page. You will have a lot of alert messages to help you debug and understand my code. I have modified an existing code, Please ignore what seems irrelevant to you. Only the name field shall be required to carry out the tests. Do let me know if you need clarifications.

While testing, please select the text so that you dont select a space along with the word, which usually happens when selecting with a double click.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
function getPreviousWord()
{
    alert("inside getPreviousWord");
    var sel = window.getSelection().toString();
    alert("selected word is: "+ sel);
    var x=document.getElementById("1111");
    alert("x= " +x);
    var currentTag=x.tagName;
    alert("Current tagname is: "+currentTag);
    currentTag=currentTag.toLowerCase();
    alert("Current tagname (lowered) is: "+currentTag);
    var completeList=document.getElementsByTagName(currentTag); 
    var converted=completeList.toString();
    alert("complete List is: "+completeList);
    alert ("coneverted = "+converted);
    var cur=0;
    var next=0;
    var i=0;
    var word1="";
    var word2="";
    var j=0;
    var found= false;
    for(i=0;i<completeList.length;i++)
        {
        var temp=completeList[i].value.toString()+" ";
        alert("temp= "+temp);
        for(j=0;j<temp.length;j++)
        {
        if(temp.substring(j,j+1)==" ")
            {   
                alert("Blank space found");
                next=j;
                alert("next= "+j);
                word1=word2;
                word2=temp.substring(cur,next);
                alert("word1= "+word1 +" and word2= "+ word2);
                cur=j+1;
                if(word2==sel)
                    {
                    alert("previous word is: "+ word1);
                    found= true;
                    break;
                    }
                else
                    {
                    alert("sel!=temp");
                    }

                }

        }
        if(found==true)
            {
            alert("Breaking outer loop");
            break;
            }

        }
}

</script>
<title>Hello World</title>
</head>
<body bgcolor="beige">
   <h1>Employee Details</h1>

<form  action="hello" name="frm" onSubmit="return validate()">

      <label>Please enter your name</label><br/>

    <input type="text" name="name" id="1111" onselect="getPreviousWord()"/><font size="4" color="red"> <div id="error"> </div></font>
       <br/>
      <label id="abc">Employee ID:</label><br/>
       <input type="text" name="empId"/><br/>

       <label>Email Id:</label><br/>
       <input type="text" name="email">
       <br/>
       <label>Phone Number:</label><br/>
       <input type="text" name="phone">
       <br/>
       <br/>

       <br/>
       <input type= "button" value="Check" onclick="return validate()">
      <input type="submit" value="Submit"/>

      <s:fielderror>
        <s:param> name</s:param>
       </s:fielderror>
   </form>
</body>
</html>
hchawla
  • 126
  • 8
-1
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the array values after the split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "Abdul Naeem";
    var res = str.split(" ");
    for(i=0;i<res.length;i++)
    {

    alert(res[i]);
    }
    //document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>
kki3908050
  • 165
  • 2
  • 9
-1

Try This in JS with Jquery :

var a="Name : Abdul Naeem";
var sp="Naeem";
$(function(){
var x=a.split(sp);
    z=x[0].split(" ");
    alert(z[z.length-2]);
});

Demo in JSFIDDLE

kupendra
  • 1,002
  • 1
  • 15
  • 37