#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2011
    Posts
    105
    Rep Power
    51

    Get text surrounding selected text


    Hi guys,

    Im working on an article spinner in HTML and jQuery. Whenever a user selects a word in the article textarea, you can look up synonyms for it.

    To make it more user friendly, I want to show a small part of the text surrounding the selected word in a DIV, so the user will remember for what sentence he is looking for synonyms

    However, I can't find a proper way to do this. So the question: how can I retrieve text surrounding a selected word in a textarea?

    Is this even possible?

    Im using the RangyInputs Library to manipulate selections in the textarea
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    Hi,

    um, haven't you looked into that library yet? There's a getSelection() method, which returns the start and end index of the selection. With that, you can select the corresponding substring of the textarea content.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2011
    Posts
    105
    Rep Power
    51
    I know, but there is no clean method to get the text between two points without altering the current selection
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
  8. #5
  9. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2011
    Posts
    105
    Rep Power
    51
    How can I use that to get text outside of the current selection?
    Post to Facebook using a Nokia 3310
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1046
    You have the full content of the textarea (fetched with JavaScript's native "value" method or whatever jQuery method you might be using). You have the start and end index of the selection. And you have a method to retrieve a substring between two indices.

    With that, you can get any surrounding text you want. If you want the 5 characters before and after the selection, substract 5 from the start, add 5 to the end, and then use substring() with those two numbers.
  12. #7
  13. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2011
    Posts
    105
    Rep Power
    51
    Thanks! That did it. I got this code now:

    Code:
    $(\"#txt\").mouseup(function() {
    	$(\"#txt\").focus();
    	var sel = $(\"#txt\").getSelection();
    	var sentence = $(\"#txt\").val().substring(sel.start - 10,sel.end + 10);
    	alert(sentence);
    });

    Comments on this post

    • Jacques1 agrees : That looks good.
    Last edited by Rhytz; January 9th, 2013 at 08:28 AM.
    Post to Facebook using a Nokia 3310

IMN logo majestic logo threadwatch logo seochat tools logo