Reputation: 996
I'm trying to make some simple jquery script that replaces a specific string in the textarea. I've got this know:
$("textarea").bind("keyup", function() {
var text = $(this).val();
text = text.replace(/,,/g, "′");
$(this).val(text);
});
This replaces ,,
into the unicode symbol ′
. This works, except that the cursors position moves to the last character of the textarea everytime there is a replacement. I want that the cursors goes just after the ′
when there is a replacement. How could I do this ?
Here is my jsfiddle: http://jsfiddle.net/zvhyh/
Edit: thanks for the help guys. I use this now: http://jsfiddle.net/zvhyh/14/
Upvotes: 0
Views: 1447
Reputation: 28437
Here is your updated fiddle: http://jsfiddle.net/zvhyh/10/
The key is to use selectionStart
to get the current position of cursor and setSelectionRange
to place the cursor in that position later on.
// get current cursor position
var pos = $(this).val().slice(0, this.selectionStart).length;
// replace the text
$(this).val($(this).val().replace(/,,/g, "′"));
// reset the cursor position
this.setSelectionRange(pos, pos);
Hope that helps.
Update:
Because two characters are being replaced by one character, in the above code the cursor position will skip one character to right. One workaround is to first check if a ",," combo is there, and then use the position as one character before.
Updated fiddle: http://jsfiddle.net/zvhyh/13/
if (text.indexOf(",,") > 0) {
...
pos--;
..
Upvotes: 1
Reputation: 2419
Here is my take on it:
$("textarea").bind("keyup", function() {
var cursorPosition = $('textarea').prop("selectionStart");
var text = $(this).val();
if (text.indexOf(',,') > -1) {
text = text.replace(/,,/g, "′");
$(this).val(text);
$('textarea').prop("selectionStart", cursorPosition - 1);
$('textarea').prop("selectionEnd", cursorPosition - 1);
}
});
Upvotes: 1