There is a textarea with id = "test".

1) How to make so that when you type in quotes (single or double) in textarea, a pair of quotes is substituted at once, and the cursor is positioned between them (as in development environments, ala sublime)?

2) How to make that if you enter a couple of quotes, then there would be no 4 of them in the end, but the second quotes would just go away (and in the sum of them there would be 2 left - again, as implemented in the code editors).

those. it is necessary that it be like this:

'→'. ' (where. - cursor position)

"→". "

"" → "".

    1 answer 1

    Made an example of working with "." - point the cursor, when entering " added "" , the same with single quotes, between them the cursor, but therefore you can go further with the example and sharpen it for yourself. I hope that it helped

     var input = document.getElementById('test'); input.addEventListener("keypress", function(evt){ if(evt.which === 34) { input.value = input.value + "\""; setCaretPosition(input, input.value.lastIndexOf('"')) } if(evt.which === 39) { input.value = input.value + "'"; console.log(input.value.lastIndexOf("'")) setCaretPosition(input, input.value.lastIndexOf("'")) } }) function setCaretPosition(elem, caretPos) { var range; if (elem.createTextRange) { range = elem.createTextRange(); range.move('character', caretPos); range.select(); } else { elem.focus(); if (elem.selectionStart !== undefined) { elem.setSelectionRange(caretPos, caretPos); } } } 
     <textarea id="test"></textarea> 

    • Thank you, just what you need! - Ya_O