Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent selected text 4 spaces

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.

like image 977
Bojangles Avatar asked Jul 16 '11 15:07

Bojangles


2 Answers

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?

like image 121
marc Avatar answered Sep 18 '22 02:09

marc


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)
   );
}
like image 41
Spudley Avatar answered Sep 19 '22 02:09

Spudley