我正在使用 JavaScript,我的文本是:
Dana's places, we're having people coming to us people wanna buy condos. They want to move quickly and we're just losing out on a lot of great places. Really what would you say this?
如果我的索引位置是 6
,我只想得到第一句话:Dana's places, we're having people come to us people wanna buy condos.
如果我的索引位置是 80
,我只想得到第二句话:他们想快速行动,而我们只是失去了很多好地方。
如何根据位置解析句子?
最佳答案
如果我没理解错的话,你应该可以
分期。 获取字符串的长度。 根据句子长度确定索引的位置。
考虑到您需要拆分 "?, !"同样,您只需要遍历句子并将它们进一步扁平化。阿卡,再次 split 。
老实说,使用正则表达式和组可能更干净。
这是正则表达式版本
const paragraph = "Dana's places, we're having people coming to us people wanna buy condos. They want to move quickly and we're just losing out on a lot of great places. Really what would you say this?"
/**
* Finds sentence by character index
* @param index
* @param paragraph
*/
function findSentenceByCharacterIndex(index, paragraph) {
const regex = /([^.!?]*[.!?])/gm
const matches = paragraph.match(regex);
let cursor = 0;
let sentenceFound;
for (const sentence of matches) {
sentenceFound = sentence;
cursor += sentence.length;
if( cursor > index )
{
break;
}
}
return sentenceFound;
}
const found = findSentenceByCharacterIndex(5, paragraph);
关于javascript - 给定一个索引位置,我如何拆分出该位置所在的句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744344/