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

前端 未结 3 557
孤城傲影
孤城傲影 2021-01-06 03:51

I am trying to find the textual start and end of the selection. So, in the following text, if I selected \"world! What a fine\" from within \"Hello, world! What a fine day

3条回答
  •  自闭症患者
    2021-01-06 04:42

    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] + '

    '+ select[2] + '

    ' + 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 **

提交回复
热议问题