个性化阅读
专注于IT技术分析

如何在JavaScript中使用给定索引检索字符串中最接近的单词

如果你想知道在具有指定索引号的字符串中哪个是最接近的单词, 请使用以下函数来解决问题:

/**
 * 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);
}

>>>运算符将expression1的位右移expression2中指定的位数。零从左侧填充。右移的数字将被丢弃(左操作数的值将向右移动右操作数指定的位数, 并且移位后的值将填充为零)。

你甚至可以将此属性添加到String原型中:

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, 

用法

通常, 你可以使用诸如indexOf或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.

尽管这可能不是最常见的情况, 但是如果你在onboundary事件中使用API​​(例如speechSynthesis), 该事件返回字符串中正在说出的单词的索引, 则它可能会变得有用。

赞(0)
未经允许不得转载:srcmini » 如何在JavaScript中使用给定索引检索字符串中最接近的单词

评论 抢沙发

评论前必须登录!