views:

77

answers:

2

I'm thinking if there is a way to use javascript to pick up ANY ONE sentence from a textarea simply by clicking any position within that sentence.

I'm thinking along the line of - first, get current cursor position (which I know how) - second, somehow locate the position of the previous fullstop and the next fullstop (how?) - take whatever content within the two fullstops. (how?)

Or there is a simple way to do it?

+2  A: 

I assume you already know about handling caret position and getting the content before / after the caret, so here's a pseudocode solution:

  • User clicks on textarea
  • Get current caret position
  • Store everything before caret position in variable A
  • Store everything after caret position in variable B
  • Find position of last full stop in A using lastIndexOf()
  • Find position of first full stop in B using indexOf()
  • Handle situations where full stop is not found
    • set position to 0 in case of A
    • end of string in case of B)
  • Take substring (last_pos, end_pos) from A
  • Take substring (0, first_pos) from B
  • Combine substrings.
Tatu Ulmanen
A: 

I started working on this before other people responded because I was so intrigued by it. Here is what I got to work. You can probably base your work off this and incorporate the other suggestions:

<html>
<script type="text/javascript">
function getsentence(){
 var ta = document.getElementById("ta");
 var cursor = ta.selectionStart;
 var text = ta.value;

 //Find the beginning
 var start;
 for(var i = cursor; i > 0; i--){
  if(text.charAt(i) === "."){
   start = i+2;
   break;
  }
  start = 0;
 }

 //Find end
 var end;
 for(var i = cursor; i < text.length; i++){
  if(text.charAt(i) === "."){
   end = i+1;
   break;
  }
  end = text.length;
 }
 alert(text.substring(start, end));
}
</script>
<body>
<textarea id="ta" rows="10" cols="50" onclick="getsentence()">
This is a sample. Here is sentence two. Here is sentence three. And now on to number four.
</textarea>
</body>
</html>
Ronald