Javascript 从输入中删除最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6891402/
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
Delete last character from input
提问by sir_thursday
How could I delete the last character from an input in JQuery? For example, onclick
of something, it deletes the last character (a comma in my case) from an input field.
如何从 JQuery 的输入中删除最后一个字符?例如,onclick
它从输入字段中删除最后一个字符(在我的例子中是逗号)。
回答by RiaD
$(input).val(
function(index, value){
return value.substr(0, value.length - 1);
})
回答by Mrchief
If you want to chop of any last character (not just comma, space), you can use slice
:
如果你想砍掉任何最后一个字符(不仅仅是逗号、空格),你可以使用slice
:
var $myInput = $('#myInput');
$myInput.val($myInput.val().slice(0, -1));
You can combine it with $.trim()
to remove extra spaces:
您可以将其与$.trim()
删除多余的空格结合使用:
$myInput.val($.trim($myInput.val()).slice(0, -1));
回答by David says reinstate Monica
The following works, albeit it's perhaps a little clunky:
以下工作,虽然它可能有点笨重:
$('#idOfButtonToClick').click(
function(){
var inputString = $('#idOfInput').val();
var shortenedString = inputString.substr(0,(inputString.length -1));
$('#idOfInput').val(shortenedString);
});
Revised demo, that checks for the last character being a ,
character before truncating the string:
修改后的演示,,
在截断字符串之前检查最后一个字符是否为字符:
$('#idOfButtonToClick').click(
function(){
var inputString = $('#idOfInput').val();
if (inputString.charAt(inputString.length - 1) == ',') {
var shortenedString = inputString.substr(0,(inputString.length -1));
$('#idOfInput').val(shortenedString);
}
return false;
});
回答by nickf
These two lines will remove a trailing comma from a particular input. I'll leave it up to you to decide when it needs to be run (on change/on button click, etc).
这两行将从特定输入中删除尾随逗号。我将让您决定何时需要运行它(更改/单击按钮等)。
var $theInput = $('#myInput');
$theInput.val($theInput.val().replace(/,$/, ''));
If you also want to get rid of any possible whitespace at the end, change the regex to this:
如果您还想在最后去掉任何可能的空格,请将正则表达式更改为:
/\s*,\s*$/
回答by Manuel Jose Loura Lucas
function back_space() {
var arrayexit = document.getElementById("tbtwo").value;
for (var i = 0; i < arrayexit.length; i++)
{
var output = arrayexit.slice(0, -1);
document.getElementById("tbtwo").value = output;
}
}
回答by d?lo sürücü
Html code
html代码
<input oninput="remove(this.value)" type="text" id="mytext" />
Js code
js代码
function remove(val) {
document.querySelector("#mytext").value = val.slice(0, -1);
}