user828647
user828647

Reputation: 515

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. 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? Thanks for any help in advance!

Upvotes: 0

Views: 1097

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54734

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.

Upvotes: 4

Bill
Bill

Reputation: 25565

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.

Upvotes: 0

Related Questions