0

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/

90intuition
  • 966
  • 3
  • 12
  • 25
  • possible duplicate of [update textarea value, but keep cursor position](http://stackoverflow.com/questions/3286595/update-textarea-value-but-keep-cursor-position) – adeneo Nov 26 '13 at 15:43
  • I would check this out: http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea – MonkeyZeus Nov 26 '13 at 15:44
  • Looks like a duplicate of [set cursor to specific line in a textarea](http://stackoverflow.com/questions/17858174/set-cursor-to-specific-position-on-specific-line-in-a-textarea) as well – Scott Mermelstein Nov 26 '13 at 15:47

2 Answers2

1

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--;
..
Abhitalks
  • 27,721
  • 5
  • 58
  • 81
1

Here is my take on it:

http://jsfiddle.net/zvhyh/11/

$("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);
    }
});
Pedro Estrada
  • 2,384
  • 2
  • 16
  • 24