如何使用正则表达式删除字符串中的字母,破折号和美元符号? [英] How do I remove letters and dashes and dollar signs in a string using a regular expression?

查看:243
本文介绍了如何使用正则表达式删除字符串中的字母,破折号和美元符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找所有字母,破折号和美元符号,并将其从文本框中删除.

I'm trying to find all letters and dashes and dollar signs and remove them from a text box.

function numbersOnly()
{
    if ($('.sumit').val().indexOf([A-Za-z-$])) {
        $('.sumit').val().replace([A-Za-z-$], "");
    }
}

这就是我所拥有的,我很确定这是错误的.我对正则表达式不太满意,但是我正在尝试学习它们.有人想要帮助我并让我开始完成此功能吗?

That's what I've got and I'm pretty sure it's wrong. I'm not too great with regular expressions, but I'm trying to learn them. Does anyone want to help me out and get me started with completing this function?

所以..您已经得到了输入.

So.. You've got the inputs.

<div class="numInputRight"><input type="text" class="sumit" name="sumAmount1"></div>
<div class="numInputRight"><input type="text" class="sumit" name="sumAmount2"></div>
<div class="numInputRight"><input type="text" class="sumit" name="sumAmount3"></div>

然后您具有以下功能:

numbersOnly = function()
{
  $('.sumit').val().replace(/[A-Za-z$-]/g, "");
  alert($('.sumit').val());
  return false;
}   

我正在警告确定替换是否有效.不是.

I'm alerting to determine if the replace is working. It's not.

推荐答案

Mark对所有非数字字符都执行此操作.如果您只想取出字母,破折号和$(例如,但保留小数),则可以对原始文件进行以下修改:

Mark's does it for all non-digits. If you want to only take out letters, dashes and $, (but leaving decimals, for example), this modification to your original should do it:

$('.sumit').val().replace(/[A-Za-z$-]/g, "");

(出于个人原因,我个人更喜欢Mark的最新答案;您捕捉到了用这种方式无法预测的所有内容.)

(And I personally prefer Mark's updated answer for the same reason he does; you catch everything you can't predict that way.)

对于您的更新问题,值未更改的原因是因为val()返回了新字符串.不会更改实际值.为此,请尝试:

For your updated question, the reason the values aren't changing is because val() returns a new string. It will not change the actual value. To do that, try:

$('.sumit').each(function() { 
    $(this).val($(this).val().replace(/[A-Za-z$-]/g, "")); 
});
alert($('.sumit').val());

我也将它放入了each()调用中,以便每个元素都可以单独完成.

I also made it into an each() call so that every element would be done individually.

这篇关于如何使用正则表达式删除字符串中的字母,破折号和美元符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆