Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace the very last character in a text area field?

Tags:

javascript

For examples

test1, test2, test3, test4,

How do I replace the very last character (comma) with a period?

like image 794
user406151 Avatar asked Jul 06 '11 21:07

user406151


3 Answers

This removes the trailing comma if any and adds a period:

textarea.value = textarea.value.replace(/,$/, "") + ".";

textarea.value is a string which has a replace method. As first argument, a regular expression is given (characterized by a single leading /) which matches a comma on the end ($). The match (if any) is replaced by nothing (removed) and a period is appended.

Beware that this code resets the scrolling (at least in Firefox) and the cursor position.

Another snippet that removed a traling comma, but which does not add a period if there is no trailing comma:

textarea.value = textarea.value.replace(/,$/, ".");
like image 91
Lekensteyn Avatar answered Nov 10 '22 05:11

Lekensteyn


You can use .slice() to remove the last character, then just concatenate the period.

var ta = document.getElementById('mytextarea');

ta.value = (ta.value.slice(0,-1) + '.');
like image 9
user113716 Avatar answered Nov 10 '22 04:11

user113716


var yourTextarea = document.getElementById('textareaId'); // get your textarea element
var val = yourTextarea.value; // get text, written in textarea
val = val.slice(0,-1); // remove last char
val += charToReplace; // add char, that you want to be placed instead of comma
yourTextarea.value = str; // set just edited text into textarea
like image 3
Sergey Metlov Avatar answered Nov 10 '22 04:11

Sergey Metlov