Как получить ближайшее слово в строке с заданным индексом в 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.

Хотя, возможно, это не самый распространенный случай, он может оказаться полезным, если вы используете API-интерфейс, подобный speechSynthesis в пограничном событии, которое возвращает индекс слова, произносимого в строке.

Ссылка на основную публикацию
Adblock
detector