luqita
luqita

Reputation: 4085

javascript regular expression

How can I modify the following so that it keeps the character '.'?

This my regular expression:

a.replace(/[^\d]/g,'');

I am learning them, and I can see that it will keep the numbers from 0 to 9 only. Which is correct for my needs, however sometimes I need to pass a number such as 1.44 and this will just erase the '.'.

Thanks!

Upvotes: 1

Views: 157

Answers (4)

nnnnnn
nnnnnn

Reputation: 150070

Just add the full-stop to the list in the square brackets (within the brackets you shouldn't need to escape it, though elsewhere in a regular expression you'd need to escape it with a backslash):

a.replace(/[^\d.]/g,'');

Upvotes: 0

Jared Ng
Jared Ng

Reputation: 5071

You're looking for a.replace(/[^\d\.]/g,'');

Upvotes: 0

Eugene
Eugene

Reputation: 11280

try this:

a.replace(/[^\d.]/g,'');

Upvotes: 0

cdhowie
cdhowie

Reputation: 169403

[^\d] is a character class that means anything except (^) digits (\d). You want it to remove anything except digits and periods, so just add the . to the character class:

a.replace(/[^\d.]/g,'');

Upvotes: 3

Related Questions