简体   繁体   English

如何从文本区域中突出显示的文本中获取邻居字符?

[英]How to get neighbor character from highlighted text in the textarea?

This returns highlighted text: 这将返回突出显示的文本:

 function getSelection(elem) { var selectedText; if (document.selection != undefined) { // IE elem.focus(); var sel = document.selection.createRange(); selectedText = sel.text; } else if (elem.selectionStart != undefined) { // Firefox var startPos = elem.selectionStart; var endPos = elem.selectionEnd; selectedText = elem.value.substring(startPos, endPos) } return selectedText; } $(document).on('mousedown', 'button', function(e) { var selection = getSelection( $('#txtarea').get(0) ); alert(selection); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txtarea">this is a test</textarea> <button>highlighted text</button> 

Now I need to select adjacent character from selected/highlighted text. 现在,我需要从选中/突出显示的文本中选择相邻字符。 for example if his is at is selected, then I need to get both t (L) and e (R) characters. 例如,如果选择his is at ,则我需要同时获取t (L)和e (R)字符。 How can I do that? 我怎样才能做到这一点?

Get the value of the textarea using 使用获取文本区域的值

var preview=document.getElementById("txtarea");

Get it's content using 使用获取内容

var str=preview.value

The string to be matched 要匹配的字符串

x="his is a t"

Using indexOf to get the character at which it starts 使用indexOf获取开始的字符

res=str.indexOf(x)

this returns 1 这将返回1

To find the character before it(check for res!=0) 要找到它之前的字符(检查res!= 0)

str.charAt(res-1)

Returns "t" 返回“ t”

For the last char 对于最后一个字符

str.charAt(res+x.length)

Returns "e" 返回“ e”

Try this one 试试这个

 function GetSelection() { var selection = ""; var textarea = document.getElementById("myArea"); if ('selectionStart' in textarea) { // check whether some text is selected in the textarea if (textarea.selectionStart != textarea.selectionEnd) { selection = textarea.value.substring(textarea.selectionStart - 1, textarea.selectionEnd + 1); } } else { // Internet Explorer before version 9 // create a range from the current selection var textRange = document.selection.createRange(); // check whether the selection is within the textarea var rangeParent = textRange.parentElement(); if (rangeParent === textarea) { selection = textRange.text; } } if (selection == "") { alert("No text is selected."); } else { alert("The current selection is: " + selection); } } 
 <body> <textarea id="myArea" spellcheck="false">Select some text within this field.</textarea> <button onclick="GetSelection ()">Get the current selection</button> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM