How to find the selection text beginning and end positions in Javascript?

给你一囗甜甜゛ 提交于 2019-11-30 23:34:39

I use this:

/* Returns 3 strings, the part before the selection, the part after the selection and the selected part */
function getSelected()
{
  var u     = editor.val();
  var start = editor.get(0).selectionStart;
  var end   = editor.get(0).selectionEnd;

  return [u.substring(0, start), u.substring(end), u.substring(start, end)];
}

where editor is $("#editor") or whatever ID your textarea / input field may have.

Usage:

var select = getSelected()
editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);

Will wrap selected text in H1. If nothing is selected it will just add empty H1, but you can add checks and functionality to your liking.

** Not tested in all browsers, works in Chrome though **

Tim Down

This is possible but slightly complicated with contenteditable HTML content (as opposed to text within an <input> or <textarea> element). Here's a simple cross-browser implementation:

https://stackoverflow.com/a/4812022/96100

But I know a jQuery plugin that aims your problem and much more - https://github.com/localhost/jquery-fieldselection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!