如何用window.getSelection()获取选中词及前后相邻词
Great question! Using window.getSelection() to target the selected word and its immediate neighbors is totally feasible—let’s walk through a practical, API-focused solution (no regex required for the core selection logic):
Step 1: Capture the selection and expand to the full word
First, we grab the user’s selection, then expand it to cover the entire word (in case they only selected part of it):
function getWordContext() { const selection = window.getSelection(); if (selection.rangeCount === 0) return null; // No selection made // Get the active range from the selection let range = selection.getRangeAt(0); const originalRange = range.cloneRange(); // Save a copy for later // Expand the range to include the full selected word range.modify("move", "backward", "word"); range.modify("extend", "forward", "word"); const selectedWord = range.toString().trim();
Step 2: Fetch the previous word (n-1)
Next, we reposition the range to the start of the selected word, then shift backward to capture the preceding word:
// Reset range to the start of the selected word range.setStart(originalRange.startContainer, originalRange.startOffset); // Move backward one word and expand to select it range.modify("move", "backward", "word"); range.modify("extend", "forward", "word"); const previousWord = range.toString().trim();
Step 3: Fetch the next word (n+1)
Finally, we jump to the end of the selected word and shift forward to grab the next word:
// Reset range to the end of the selected word range.setEnd(originalRange.endContainer, originalRange.endOffset); // Move forward one word and expand to select it range.modify("move", "forward", "word"); range.modify("extend", "backward", "word"); const nextWord = range.toString().trim(); return { previous: previousWord, selected: selectedWord, next: nextWord }; }
How to use it
Call the function after a user makes a selection (e.g., on a mouseup event):
document.addEventListener("mouseup", () => { const context = getWordContext(); if (context) { console.log("Previous word:", context.previous); console.log("Selected word:", context.selected); console.log("Next word:", context.next); } });
Edge Cases to Keep in Mind
- If the selected word is the first in the sentence,
previousmight return an empty string or whitespace—add a check (likepreviousWord.match(/\w+/)?.[0]) to filter out non-word characters. - If it’s the last word,
nextwill be empty for the same reason. - If the user selects multiple words, this code will target the first word in the selection. Adjust the range logic if you need to handle multi-word selections differently.
For your example sentence "this is a sentence", selecting "is" would return:
{ previous: "this", selected: "is", next: "a" }
内容的提问来源于stack exchange,提问作者Colin Burke

