我想补充一点,不使用正则表达式的答案分割 字符串,因为这样做效率很低,并且可能会在较大的文本块上非常缓慢。
最有效的方法可能是使用几个循环进行搜索,只需要2遍就可以找到句子的结尾。
var sentenceFromPos = function (s, pos) {
var len = s.length,
start,
end,
char;
start = pos;
end = pos;
while (start >= 0) {
char = s.charAt(start);
if (char === '.' || char === '?' || char === '!') {
break;
}
start -= 1;
}
while (end < len) {
char = s.charAt(end);
if (char === '.' || char === '?' || char === '!') {
break;
}
end += 1;
}
return s.substring(start + 1, end + 1).trim();
};
var phrase = 'This is the first sentence. And this is the second! Finally, this is the third sentence';
console.log(sentenceFromPos(phrase, 10));
console.log(sentenceFromPos(phrase, 33));
console.log(sentenceFromPos(phrase, 53));
只需按'。?!'分割并添加长度,直到获得长度> =当前位置。 – ndn
试试[这个演示](http://jsfiddle.net/qqzssoyv/) - 它是你在找什么? –
@stribizhev完美......我也觉得有点愚蠢,因为没有意识到解决方案一开始就有多简单。无论如何,如果你想将它写成答案,我会奖励给你。 – Gordo