I use this:
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 is the editor $("#editor") or any other identifier that your textarea / input field may have.
Using:
var select = getSelected() editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]);
Flips the selected text to H1. If nothing is selected, it will simply add an empty H1, but you can add checks and functions to your liking.
** Not tested in all browsers, works in Chrome, although **
source share