I can not figure out why when inserting quotes in the middle of the text, the cursor goes to the end of the text, how to fix it?

function replaceQuotes(input) { input.value = changeQuotes(input.value); } function changeQuotes(text) { var el = document.createElement("textarea"); el.innerHTML = text; for (var i = 0, l = el.childNodes.length; i < l; i++) { if (el.childNodes[i].hasChildNodes() && el.childNodes.length > 1) { el.childNodes[i].textContent = changeQuotes(el.childNodes[i].textContent); } else { el.childNodes[i].textContent = el.childNodes[i].textContent.replace(/\x27/g, '\x22').replace(/(\w)\x22(\w)/g, '$1\x27$2').replace(/(^)\x22(\s)/g, '$1»$2').replace(/(^|\s|\()"/g, "$1«").replace(/"(\;|\!|\?|\:|\.|\,|$|\)|\s)/g, "»$1"); } } return el.textContent; } 
 textarea{ width: 80%; } 
 <p> Пример текста: </br> "текст" </br> если этому тексту добавить кавычки</br> "то курсор переместиться в конец этого текста"</br> </p> <textarea onkeyup="replaceQuotes(this)" rows="5" ></textarea> 

  • one
    input.value = changeQuotes(input.value); overwrite all the text, then sets the cursor to the end of the line. The same thing happens when you вставке , when you копируешь - Evgeny Nikolaev

1 answer 1

 function replaceQuotes(textarea){ let text = textarea.value; let index = text.search(/[\"]/); textarea.value = text.replace(/\x27/g, '\x22').replace(/(\w)\x22(\w)/g, '$1\x27$2').replace(/(^)\x22(\s)/g, '$1»$2').replace(/(^|\s|\()"/g, "$1«").replace(/"(\;|\!|\?|\:|\.|\,|$|\)|\s)/g, "»$1"); if(index !== -1){ textarea.selectionStart = textarea.selectionEnd = index + 1; //устанавливаем курсор на место где была кавычка } } 
 <textarea onkeyup="replaceQuotes(this)" rows="5" ></textarea>