简体   繁体   English

使用Javascript替换textarea中的文本

[英]Replace text in textarea using Javascript

I need to replace all the matches of a regular expression till the caret position in a textarea using Javascript. 我需要使用Javascript替换正则表达式的所有匹配项,直到textarea中的插入符位置。 For example, if the text in the textarea is: "6 students carry 2 books to 5 classes" and the cursor is placed on books and the regular expression is /\\d/, the numbers 6 and 2 should be replaced by, say, 4. I know the replace function and I know how to get the caret position, but how do I solve this problem? 例如,如果文本区域中的文本为:“ 6名学生携带2本书到5个班级”,并且光标位于书本上并且正则表达式为/ \\ d /,则数字6和2应该替换为,例如, 4.我知道替换功能,并且知道如何获得插入符的位置,但是如何解决此问题? Thanks for any help in advance! 感谢您的任何帮助!

textareaClicked = function(e){
    var pos = e.target.selectionStart;
    var beforeSelection = e.target.innerHTML.slice(0,pos);
    var afterSelection = e.target.innerHTML.slice(pos);
    var newHTML = beforeSelection.replace(/\d/g,4) + afterSelection;
    e.target.innerHTML = newHTML;
    e.target.setSelectionRange(pos,pos);
};

document.getElementById('foo').onclick=textareaClicked;

see it in action in this jsfiddle . jsfiddle中看到它的实际效果

There is probably a more elegant way, but I would just copy the text from the text area, split the string into two substrings at the caret position (which you said you know how to find), do the replace on the first substring and then concatenate it with the second substring. 也许有一种更优雅的方法,但是我只需要从文本区域复制文本,在插入号位置将字符串分成两个子字符串(您说过知道如何找到),在第一个子字符串上进行替换,然后将其与第二个子字符串连接。 Copy it back into the text area making sure to update the caret position appropriately. 将其复制回文本区域,确保正确更新插入符号的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM