Discuss Get text surrounding selected text in the JavaScript Development forum on Dev Shed. Get text surrounding selected text JavaScript Development forum discussing JavaScript and DHTML, AJAX, and issues such as coding cross-browser JavaScript.
Posts: 100
Time spent in forums: 1 Day 11 h 4 m 50 sec
Reputation Power: 50
jQuery - 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?
Posts: 1,881
Time spent in forums: 1 Month 2 Weeks 2 Days 8 h 22 m
Reputation Power: 813
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.
Posts: 1,881
Time spent in forums: 1 Month 2 Weeks 2 Days 8 h 22 m
Reputation Power: 813
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.