I was able to do this using selectionStart
as a key for the value of the textarea
. This way when we embed this into an event listener on click
, it will return the key
of the text string within the textarea
. 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 the textArea.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
or undefined
.
I used an event listener that listens for a click
.
const textArea = document.getElementById('textArea')
const display = document.getElementById('display')
const getSelectedText = () => {
let key = textArea.selectionStart;
const word = [];
const letters = /^[A-Za-z]+$/;
if (key < textArea.value.length && key > 0) {
while (textArea.value[key].match(letters)) {
key--
if (key < 1) {
while (textArea.value[key].match(letters)) {
word.push(textArea.value[key])
key++
}
} else if (textArea.value[key].match(letters) === null) {
key++
while (textArea.value[key].match(letters)) {
word.push(textArea.value[key]);
key++
}
}
}
}
return word.join('');
}
textArea.addEventListener('click', () => {
display.innerHTML = `<b>Your selected text is:</b> <i>${getSelectedText()}</i>`
})
<textarea id='textArea' rows="7" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
<div id="display"></div>