I want to indent the selected text in a <textarea> by 4 spaces, just like StackOverflow does for code, using jQuery. I'm doing this to create a text editor similar to SO's, but with only basic functionality.
I don't want links or suggestions to ready-made editors; I've got everything I want but my problem above. Can someone give me some pointers as to how I'd indent the selected text, or some code snippets?
Thanks.
function indentSelection() {
    var selection = $(this).getSelection().text;
    var textarea = $(this);
    var result = '';
    var lines = selection.split('\n');
    var space = '    ';
    for(var i = 0; i < lines.length; i++)
    {
        result += space + lines[i] + '\n';
    }
    var new_text = textarea.val().split(selection).join(result);
    textarea.val(new_text);
}
Should do it. For an example on how to acquire the selected text (this has been shortened here) see How to get selected text in textarea?
I'd use a regex replace() for this. Just replace the new-line with a new-line plus four spaces:
function indentSelection(textarea) {
  $(textarea).val(
        $(textarea).val().substring(0, textarea.selectionStart)
          + $(textarea).getSelection().text.replace(/\n/m,'    \n')
          + $(textarea).val().substring(textarea.selectionEnd)
   );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With