is there a way to get a string under current cursor position inside a textarea
for example – click on lorem
– console should be lorem
essentially, something like this:
let a = previous space or line break from cursor position
let b = next space or line break from cursor position
console.log(text from a to b);
$('#ed').on('click', function(){
//let a = previous space or line break from cursor position
//let b = next space or line break from cursor position
//console.log(text from a to b);
});
#ed{
display:block;
width:100%;
padding:9px;
height:50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id='ed'>
lorem ipsum
https://google.com
</textarea>
I was able to do this using
selectionStart
as a key for the value of thetextarea
. This way when we embed this into an event listener onclick
, it will return thekey
of the text string within thetextarea
. We create a function that looks for a match of letters, if we have a match on the key where the cursor is placed, then we iterate backwards until there is no longer a letter, this gives us the beginning of the word. Then we reiterate forward until there is no match and push the values of thetextArea.value[key]
into an array,join
this array to create a string of the characters that make up that word.Also need a conditional to make sure we are within the length of the string start and end, less an error is thrown as the value will be
null
orundefined
.I used an event listener that listens for a
click
.