如何从textarea中突出显示的文本中获取邻居角色?

时间:2016-01-18 04:04:28

标签: javascript jquery regex

这将返回突出显示的文字:

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>

现在我需要从所选/突出显示的文本中选择相邻的字符。例如,如果选择了his is a t,那么我需要同时获得t(L)和e(R)字符。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

使用

获取textarea的值
var preview=document.getElementById("txtarea");

使用

获取内容
var str=preview.value

要匹配的字符串

x="his is a t"

使用indexOf获取它开始的角色

res=str.indexOf(x)

返回1

查找前面的字符(检查res!= 0)

str.charAt(res-1)

返回“t”

最后一个字符

str.charAt(res+x.length)

返回“e”

答案 1 :(得分:0)

试试这个

&#13;
&#13;
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);
  }
}
&#13;
<body>
  <textarea id="myArea" spellcheck="false">Select some text within this field.</textarea>
  <button onclick="GetSelection ()">Get the current selection</button>
</body>
&#13;
&#13;
&#13;