How do I replace the very last character in a text area field?
For examples
test1, test2, test3, test4,
How do I replace the very last character (comma) with a peri开发者_如何学Good?
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(/,$/, ".");
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) + '.');
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
You can check for a 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) + '.';
document.getElementsByTagName('textarea')[0].innerHTML = document.getElementsByTagName('textarea')[0].innerHTML.substr(0, document.getElementsByTagName('textarea')[0].innerHTML.length - 1)
精彩评论