I'm using JavaScript, and my text is:
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?
If I have an index position of 6
, I want to get just the first sentence: Dana's places, we're having people coming to us people wanna buy condos.
If I have an index position of 80
, I want to get just the second sentence: They want to move quickly and we're just losing out on a lot of great places.
How can I parse the sentence based on position?
If I understand correctly, you should be able to just
Split on periods. Get the length of the strings. Determine where the index lands based sentence length.
Considering you need to split on "?, !" as well, you just need to loop through the sentences and flatten them further. Aka, split again.
Honestly, probably cleaner to use a regex and group.
Here is the regex version
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);