如何从所选文本中获取邻居角色?

我有一个像这样的字符串:

var comment = 'this is a test'; 

假设this i被选中,现在我需要null (左侧)和s (右侧)。 我怎么能得到它们?


我可以像这样选择文字:

 function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } return html; } var selected_text = getSelectionHtml(); 

 document.addEventListener("click", function() { var selection = window.getSelection(); // Check if there are any ranges selected. if (selection.rangeCount > 0 && selection.type == "Range") { // Text content of the element. var text = selection.anchorNode.textContent; // selection.anchorOffset is the start position of the selection var before = text.substring(selection.anchorOffset-1, selection.anchorOffset); // selection.extentOffset is the end position of the selection var after = text.substring(selection.extentOffset, selection.extentOffset+1); // Check if there are any letters before or after selected string. // If not, change before and after to null. before = before.length === 1 ? before : null; after = after.length === 1 ? after : null; console.log(before, after); } }); 
 
this is a test

你不需要jQuery。 您只需要window.getSelection() 。 这会返回一个对象。 您可以使用window.getSelection().anchorNode.data获取周围的文本,并使用window.getSelection().anchorNode.data获取该文本中的选择索引。 把这一切放在一起,我们有

 var selection = window.getSelection(); var selectionText = selection.toString(); var surroundingText = selection.anchorNode.data; var index = selection.anchorOffset; var leftNeighbor = surroundingText[index - 1]; var rightNeighbor = surroundingText[index + selectionText.length]; 

请注意,当没有邻居字符时,您将获得undefined而不是null

 window.addEventListener("click", function(){ var selection = window.getSelection(); var selectionText = selection.toString(); var surroundingText = selection.anchorNode.data; var index = selection.anchorOffset; var leftNeighbor = surroundingText[index - 1]; var rightNeighbor = surroundingText[index + selectionText.length]; alert(leftNeighbor + " " + rightNeighbor); }); 
 
this is a test