如何使用正则表达式删除字符串中的字母,破折号和美元符号?

编程入门 行业动态 更新时间:2024-10-10 17:24:38
本文介绍了如何使用正则表达式删除字符串中的字母,破折号和美元符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

如何使用正则表达式删除字符串中的字母,破折号和美元符号?

本文发布于:2023-06-03 07:21:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/471181.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:破折号   字符串   如何使用   字母   符号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!