How do I remove letters and dashes and dollar signs in a string using a regular expression?

Viewed 51867

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>

Then you've got the function:

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.

6 Answers

This should do it

$('.sumit').val().replace(/[^\d.]/g, "");

The [^] is a negated character class so it's going to match all characters except those listed in the character class.

In this case, our character class is \d (which is the numbers 0-9) and a period (to allow decimal numbers).

I prefer this approach because it will catch anything that's not numeric rather than having to worry about explicitly listing the non-numeric characters I don't want.

If you really only want to exclude letters, $, and -, then Sean's answer is a better way to go.

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, "");

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

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());

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

Try something like this:

function numbersOnly()
{
    $('.sumit').val().replace(/[\w-$]/g, "");
}
Related