我有一串像这样的希伯来语单词:
כלל הנה השמים מספרים כבוד אל. הנה תחלה
以及该字符串中的匹配索引数组。我需要找到数组中给定位置的单词后面的单词的位置。我还需要不包含点、逗号和其他此类字符。
这些原因阻止我使用finding the word at a position in javascript的代码
编辑:
目标是修改这篇文章的函数,获取参数中位置旁边的单词的位置
这是我的最终解决方案:
String.prototype.indexOfEnd = function(string, position) {
var io = this.indexOf(string, position);
return (io == -1 ? -1 : io + string.length);
}
function getWordAt (str, pos) {
str = String(str);
pos = Number(pos) >>> 0;
var left = str.slice(0, pos).search(/[\u0590-\u05fe]+$/),
right = str.slice(pos).search(/[\s,.\t-_()]+/);
if (right < 0) {
return str.slice(left);
}
return str.slice(left, right + pos);
}
function getNextWordAt (str, pos) {
var result = getWordAt(str, pos);
for(let i=0; i<str.length - pos; i++) {
let tempWord = getWordAt(str, pos + i)
if (result != tempWord && tempWord != ' ' && tempWord != ',' && tempWord != '.' && tempWord != '') {
return [phrase.indexOfEnd(tempWord, pos), tempWord];
}
}
}
最佳答案
您不想使用的帖子的代码非常正确。但基本的正则表达式不是为希伯来语设计的。因此,您必须将“无空格”(即 /S
)自定义为您需要的字符代码范围。一项快速研究得出了您必须在正则表达式中使用的希伯来语字符排列的结果:\u0590-\u05fe
您可以使用任何所需的分隔字符(例如 [\s,.\t]+
)来扩展 \s
来表示空格、逗号、点和制表符。
编辑This Answer的代码我为您提供了以下解决方案代码(请注意,您必须向后阅读希伯来语文本):
function getWordAt (str, pos) {
// Perform type conversions.
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
nextWhitespace = pos + str.slice(pos).search(/\s/);
str = str.slice(nextWhitespace+1);
var left = str.slice(0, pos + 1).search(/[\u0590-\u05fe]+$/),
right = str.slice(pos).search(/[\s,.\t]+/);
// 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);
}
编辑:将以下行添加到代码中以获取 NEXT 单词:
nextWhitespace = pos + str.slice(pos).search(/\s/);
str = str.slice(nextWhitespace+1);
关于javascript - 在 JavaScript 位置查找下一个单词的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366373/