如何使用javascript在textarea中选择之前和之后插入文本?
选择发生在HTML表单的textarea字段中
最佳答案
请尝试以下操作:
var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";
如果要搜索+替换,则以下代码可以解决问题(在非IE浏览器中)
var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;