开发者

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.


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)
   );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜