Replace text in textarea using Javascript -


i need replace matches of regular expression till caret position in textarea using javascript. example, if text in textarea is: "6 students carry 2 books 5 classes" , cursor placed on books , regular expression /\d/, numbers 6 , 2 should replaced by, say, 4. know replace function , know how caret position, how solve problem? 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 in action in this jsfiddle.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -