Get the word pointed out by the caret position

Let's assume that you want to get the word pointed out by the caret position on a <textarea> element:

javascript
const handleText = (e) => {
    
    // Getting the element by Id  
    let textarea = document.getElementById('textarea');
    
    // Replacing line breaks with spaces to homogenize the string
    let message = textarea.value.replaceAll('\n', ' ').split(' ');
    
    // Length of the messange
    let l = message.length;
    
    // Getting caret's position
    let caret = textarea.selectionEnd;
    
    // Setting last word as an empty string
    let lastWord = '';
    
    for(var start = 0, i = caret - 1; message[i] !== ' ' && i >= 0; i --) start = i;
    for(var end   = 0, i = caret - 1; message[i] !== ' ' && i <= l; i ++) end   = i + 1;
    
    lastWord = message.substring(start, end);
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.