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/

3

2 Answers 2

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); } }); 
Sign up to request clarification or add additional context in comments.

Comments

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--; .. 

2 Comments

Now it moves one character too much to the right. If I type ,, somewhere not on the end of the textarea.
I like the simplicity of this method tough. When I do pos-1 I get very weird things.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.