For string input of \'this is a sentence\' it must return \'is\' when position is 6 or 7. When position is 0, 1, 2, 3 or 4 result must be \'this\'.
What is the easie
I had some strange behavior in the most popular answer at time of writing with getting the word if the position is at the last character of a word that isn't the last word.
Here's my rendition:
position and position-1 are at a space, the function returns [position, position]. This makes sense actually because the position does not have a word.function getWordBoundsAtPosition(str, position) {
const isSpace = (c) => /\s/.exec(c);
let start = position - 1;
let end = position;
while (start >= 0 && !isSpace(str[start])) {
start -= 1;
}
start = Math.max(0, start + 1);
while (end < str.length && !isSpace(str[end])) {
end += 1;
}
end = Math.max(start, end);
return [start, end];
}
To plug into substring, just deconstruct the returned bounds.
const myString = 'This is a sentence.';
const position = 7;
const wordBoundsAtPosition = getWordBoundsAtPosition(myString, position);
const wordAtPosition = myString.substring(...wordBoundsAtPosition); // => 'is'
I created a visualization of where the bounds returned by this method are in your string below:
function getWordBoundsAtPosition(str, position) {
const isSpace = (c) => /\s/.exec(c);
let start = position - 1;
let end = position;
while (start >= 0 && !isSpace(str[start])) {
start -= 1;
}
start = Math.max(0, start + 1);
while (end < str.length && !isSpace(str[end])) {
end += 1;
}
end = Math.max(start, end);
return [start, end];
}
function analyzeStringWithCursor(str, bounds, cursorIdx) {
document.getElementById("analysis").innerText = `
${"0123456789".repeat(Math.floor((str.length - 1) / 10) + 1)}
${str}
${" ".repeat(bounds[0])}↗${" ".repeat(bounds[1] - bounds[0])}↖
Cursor: ${cursorIdx}
getWordBoundsAtPosition("${str}", ${cursorIdx}): ${JSON.stringify(bounds)}
substring(${bounds[0]}, ${bounds[1]}): "${str.substring(...bounds)}"
`;
}
document.getElementById("input").onkeyup = e => {
analyzeStringWithCursor(
e.target.value,
getWordBoundsAtPosition(e.target.value, e.target.selectionStart),
e.target.selectionStart
);
};
Type some words below. The cursor (moved by typing or arrow keys)
indicates the current position.