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
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.
$('.sumit').val().replace(/\D/g, "");
Replaces all non numeric values from sumit value
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.
Try something like this:
function numbersOnly()
{
$('.sumit').val().replace(/[\w-$]/g, "");
}
This worked for me:
$('.sumit').val().replace(/[^\d]/g, "");
I tried Mike's answer with the capital \D instead of negating a \d first which for some reason didn't remove parenthesis and other punctuation for me. Negating \d works perfect.
If you want to keep decimals, maybe put a dot and other symbols within the square brackets too.
PS The environment in which I tested was Titanium SDK.
I really like Mark's answer. However, depending on your programming language (and RegEx engine) \d
matches characters like ४, or ৮, which are UTF-8 digits.
So if you only want digits from 0 to 9, use [^0-9.]
:
$('.sumit').val().replace(/[^0-9.]/g, "");
This is even faster if your RegEx engine is UTF-8 aware. An example Language, where this applies is python3 (http://docs.python.org/3/library/re.html - search for "\d"). The ECMA Standard, however, says that for JavaScript \d
equals [0-9]
.