Learn how to retrieve the closest word in a string with a given index (from indexOf) in Javascript.

If you want to know which is the closest word inside a string with a specified index number, the following function should do the trick for you :

/**
 * Find the word located in the string with a numeric index.
 *
 * @return {String}
 */
function getClosestWord(str, pos) {
    // Perform type conversions.
    str = String(str);
    pos = Number(pos) >>> 0;

    // Search for the word's beginning and end.
    var left = str.slice(0, pos + 1).search(/\S+$/),
        right = str.slice(pos).search(/\s/);

    // The last word in the string is a special case.
    if (right < 0) {
        return str.slice(left);
    }
    // Return the word, using the located bounds to extract it from the string.
    return str.slice(left, right + pos);
}

The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroes are filled in from the left. Digits shifted off the right are discarded (The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros).

You can even add this property to the String prototype :

String.prototype.closestWord = function (pos) {
    // Perform type conversions.
    str = String(this);
    pos = Number(pos) >>> 0;

    // Search for the word's beginning and end.
    var left = str.slice(0, pos + 1).search(/\S+$/),
        right = str.slice(pos).search(/\s/);

    // The last word in the string is a special case.
    if (right < 0) {
        return str.slice(left);
    }
    // Return the word, using the located bounds to extract it from the string.
    return str.slice(left, right + pos);
};

"Hello, how are you".closestWord(5);
// Outputs : Hello,

Usage

Normally, you can retrieve the index of a word with functions like indexOf or string.search :

var textA = "Hey, how are you today?";
var indexA = textA.indexOf("to");

var textB = "Sorry, i can't do this. Not today";
var indexB = textB.search("is");

var wordA = getClosestWord(textA,indexA);
var wordB = getClosestWord(textB,indexB);

console.log("Index A : " + indexA, wordA);
console.log("Index B : " + indexB, wordB);

// Output :
//Index A : 17 today?
//Index B : 20 this.

Although maybe this is not the most common case, it can become useful if you use API's like speechSynthesis in the onboundary event which returns the index of the word that's being spoken in a string.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors