How to replace the last character in a text area field?

For examples

test1, test2, test3, test4,

How to replace the last character (comma) with a period?

+5
source share
5 answers

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

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

textarea.valueis a string that has a method replace. The first argument is a regular expression (characterized by one leading /) that matches the comma at the end ( $). The match (if any) is replaced by nothing (is deleted) and a period is added.

Remember that this code resets the scroll (at least in Firefox) and the cursor position.

Another fragment that removes the trial comma, but which does not add a period if there is no trailing comma:

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

.slice() , .

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

ta.value = (ta.value.slice(0,-1) + '.');
+9
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
+3

You can check the comma at the end, and then replace it:

if (myString.substr(myString.length - 1, 1) == ',') {
  myString = myString.substr(0, myString.length - 1) + '.';
}

Or you can blindly replace it:

  myString = myString.substr(0, myString.length - 1) + '.';
+1
source
document.getElementsByTagName('textarea')[0].innerHTML = document.getElementsByTagName('textarea')[0].innerHTML.substr(0, document.getElementsByTagName('textarea')[0].innerHTML.length - 1)
0
source

All Articles