使用javascript在textarea中选择之前和之后插入文本
问题描述:
如何使用javascript在textarea中选择之前和之后插入文本? 选择发生在HTML表单的textarea字段中
How to insert text before and after selection in textarea with javascript? Selection occurs into a textarea field of a HTML form
答
尝试以下操作:
var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";
如果您要搜索+替换,则以下代码可以解决问题(在非IE浏览器中)
If you want to search + replace then the following code will do the trick (In non IE browsers)
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;