用 JQuery/Javascript 替换字符串中的所有逗号

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

Replace all commas in a string with JQuery/Javascript

javascriptjqueryreplace

提问by duckmike

I have a form where I have a couple hundred text boxes and I'd like to remove any commas when they are loaded and prevent commas from being entered. Shouldn't the follow code work assuming the selector is correct?

我有一个表单,其中有几百个文本框,我想在加载它们时删除所有逗号并防止输入逗号。假设选择器是正确的,下面的代码不应该工作吗?

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value.replace(",", "")
  })
  .onkeyup(function () {
      this.value.replace(",", "") 
  })
});

回答by totallyNotLizards

$(function(){
    $("input[id*=_tb]").each(function(){
        this.value=this.value.replace(/,/g, "");
    }).on('keyup', function(){
        this.value=this.value.replace(/,/g, "");
    });
});

See here for an explanation and examples of the javascript string.replace()function:

有关 javascriptstring.replace()函数的说明和示例,请参见此处:

http://davidwalsh.name/javascript-replace

http://davidwalsh.name/javascript-replace

as @Vega said, this doesn't write the new value back to the textbox - I updated the code to do so.

正如@Vega 所说,这不会将新值写回文本框 - 我更新了代码来这样做。

回答by sp00m

Use a regex with the gflag instead of a string: .replace(/,/g, "").

使用带有g标志的正则表达式而不是字符串:.replace(/,/g, "")

回答by Selvakumar Arumugam

Your code looks right except that it is not setting the value back to the input field,

您的代码看起来正确,只是它没有将值设置回输入字段,

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value = this.value.replace(/,/g, "")
  })
  .onkeyup(function () {
      this.value = this.value.replace(/,/g, "") 
  })
});

Edit:Used regex

编辑:使用正则表达式