jQuery 去除输入上的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12010275/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:11:50  来源:igfitidea点击:

Strip white spaces on input

jquery

提问by santa

I have a field that does not need any white spaces. I need to remove any as they are entered. Here's what I'm trying... no luck so far

我有一个不需要任何空格的字段。我需要在输入时删除任何内容。这就是我正在尝试的......到目前为止没有运气

$('#noSpacesField').click(function() {
    $(this).val().replace(/ /g,'');
});

回答by Kyle

Use jQuery trim to remove leading and trailing white space

使用 jQuery 修剪去除前导和尾随空格

$.trim(" test case "); // 'test case'

To remove all whitespace...

要删除所有空格...

" test   ing  ".replace(/\s+/g, ''); // 'testing'

To remove whitespace as it is entered...

要在输入时删除空格...

$(function(){
  $('#noSpacesField').bind('input', function(){
    $(this).val(function(_, v){
      return v.replace(/\s+/g, '');
    });
  });
});

Live Example

现场示例

回答by Bot

$('#noSpacesField').keyup(function() {
  $(this).val($(this).val().replace(/ +?/g, ''));
});

This will remove spaces as you type, and will also remove the tab char.

这将在您键入时删除空格,并且还将删除制表符。

回答by Alfiian

If you only wanna put numbers, try this! :D

如果你只想输入数字,试试这个!:D

$("#id").keyUp(function(){
   if(isNaN($(this).val())) {
     $(this).val(0);
   }
   $(this).val($(this).val().replace(/ +?/g, ''));
})