使用javascript在textarea中选择之前和之后插入文本 [英] Insert text before and after selection in textarea with javascript

查看:46
本文介绍了使用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;

这篇关于使用javascript在textarea中选择之前和之后插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆