@uiw/react-md-editor
Version:
A markdown editor with preview, implemented with React.js and TypeScript.
31 lines (24 loc) • 864 B
text/typescript
import { TextRange } from '../commands';
export default function getSurroundingWord(text: string, position: number): TextRange {
if (!text) throw Error("Argument 'text' should be truthy");
const isWordDelimiter = (c: string) => c === ' ' || c.charCodeAt(0) === 10;
// leftIndex is initialized to 0 because if selection is 0, it won't even enter the iteration
let start = 0;
// rightIndex is initialized to text.length because if selection is equal to text.length it won't even enter the interation
let end = text.length;
// iterate to the left
for (let i = position; i - 1 > -1; i--) {
if (isWordDelimiter(text[i - 1])) {
start = i;
break;
}
}
// iterate to the right
for (let i = position; i < text.length; i++) {
if (isWordDelimiter(text[i])) {
end = i;
break;
}
}
return { start, end };
}