Javascript 如何替换文本区域字段中的最后一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6603336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace the very last character in a text area field?
提问by user406151
For examples
举些例子
test1, test2, test3, test4,
测试 1、测试 2、测试 3、测试 4、
How do I replace the very last character (comma) with a period?
如何用句点替换最后一个字符(逗号)?
回答by Lekensteyn
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.
textarea.value
是一个有replace
方法的字符串。作为第一个参数,给出了一个正则表达式(以单个前导为特征/
),它与末尾的逗号 ( $
)匹配。匹配项(如果有)没有替换(删除)并附加一个句点。
Beware that this code resets the scrolling (at least in Firefox) and the cursor position.
请注意,此代码会重置滚动(至少在 Firefox 中)和光标位置。
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(/,$/, ".");
回答by user113716
You can use .slice()
to remove the last character, then just concatenate the period.
您可以使用.slice()
删除最后一个字符,然后连接句点。
var ta = document.getElementById('mytextarea');
ta.value = (ta.value.slice(0,-1) + '.');
回答by Sergey Metlov
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
回答by Kon
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) + '.';
回答by powtac
document.getElementsByTagName('textarea')[0].innerHTML = document.getElementsByTagName('textarea')[0].innerHTML.substr(0, document.getElementsByTagName('textarea')[0].innerHTML.length - 1)