How to get line under cursor in input field with JavaScript

I can get the actual position of the cursor in the input field. How can I get the full word on this post. For example, my input has the following text: Hello World

and the cursor is at position 2. How can I get Hello



source to share

4 answers

Came up with a small piece. I split the string by the cursor position and got the last characters from the first substring and the first from the second.

    var value = $(el).val()
    var split =  el.selectionStart
    var a = value.substring(0, split).match(/[A-Za-z]*$/)[0]
    var b = value.substring(split).match(/^[A-Za-z]*/)[0]
    console.log(a + b)




function getWord (str, curPos) {
    var startIndex = (function _this (pos) {
        if (!str.substring(pos, pos + 1).match(/[A-Za-z]/)) {
            return pos + 1;
        } else if (pos === 0) {
            return 0;
        } else {
            return _this(pos - 1);
    })(curPos - 1);
    var endIndex = (function _this (pos) {
        if (!str.substring(pos, pos + 1).match(/[A-Za-z]/) || pos === str.length) {
            return pos;
        } else {
            return _this(pos + 1);
    })(curPos + 1);

    return str.substring(startIndex, endIndex);


See a working example here:

Here's what's going on. getWord

It takes the input string, str

and the current cursor position curPos

. It then uses two recursive anonymous functions to insert each path into the string until it hits the beginning and end of the string. Technically they are called "Funciton Named Expressions" ( see here ) and allow you to recursively call a function even if you don't want to use it and want to store the function object for later use. Then, given those two indices, getWord

it uses the method again substring

to pass the word from the original str




The following works by looking for the first space character to the left and right of the starting position and returns the string in between. It considers any sequential character string denoted by spaces and will work even if the input is alphanumeric:

function myGetWord(aString,aPos){
    Nstr = aString.length;
        var start = aPos;
        var end = aPos;
        while (start>0 && aString[start]!=" ")
        while (end<Nstr && aString[end]!=" ")
    return aString.substring(start,end);        




Try this:

var el=document.getElementById('el');
var run=document.getElementById('run');

function findWord(str,pos){
    var words=str.split(' ');
    var offset=0;
    var i;
        if (offset>pos) break;

    return words[i];

    run.value='Word at cursor: '+findWord(el.value,el.selectionStart);




All Articles