I want to defer selected text in <textarea>4 spaces, like StackOverflow for code using jQuery. I am doing this to create a text editor similar to SO, but with basic functions.
<textarea>
I do not need links or suggestions for ready-made editors; I have everything I want, but my problem is higher. Can someone give me some pointers on how I printed the selected text or code snippets?
Thank.
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); }
Gotta do it. For example, how to get selected text (here it was shortened); see How to get selected text in a text box?
regex replace(). :
replace()
function indentSelection(textarea) { $(textarea).val( $(textarea).val().substring(0, textarea.selectionStart) + $(textarea).getSelection().text.replace(/\n/m,' \n') + $(textarea).val().substring(textarea.selectionEnd) ); }