【如何在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), 该事件返回字符串中正在说出的单词的索引, 则它可能会变得有用。
推荐阅读
- 在JavaScript中正确创建URL标记(包括UTF-8的音译)
- JavaScript承诺简介
- 如何以最佳方式使用JavaScript和jQuery遍历对象
- 如何在浏览器中使用JavaScript读取计算机文件
- 深入理解Socket下的TCP/IP通信原理及参数优化
- (总结)绕过CDN查找真实IP
- 算法奥义(滑动窗口中位数与滑动魔方)
- 高级数据结构(Ⅱ)优先队列
- 高级数据结构线段树