1

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!

4 Answers 4

3

[^\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,'');
Sign up to request clarification or add additional context in comments.

4 Comments

Yep, this is what I would do as well
That adds a dot before the number, so for example 14.4 becomes .14.4
@luqita It shouldn't... are you sure you copied the code exactly? Also, while periods don't have to be escaped in character classes (square brackets), remember that in general . stands for "any single character" in a regex. If you mean a literal period outside of square brackets, remember to escape it: \.
@luqita: No it does not; something else in your code must be doing that. See this jsfiddle for proof. Click the button, then enter a number and it will remove all of the non-numbers and non-periods.
0

try this:

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

Comments

0

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

3 Comments

I do it out of habit. It works with or without it, after all.
It is not a good habit to get into, because it betrays a lack of understanding.
@tchrist I have to say that's subjective. Besides, why memorize two rules (1. period is . inside a character class 2. period is \. outside a character class) when you can just always use a \. as a literal period? I see where you're coming from, but sometimes things are done for reasons other than "it's required by syntax".
0

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

3 Comments

Wouldn't the full-stop always mean "any character", or is that not true in square brackets?
The special meaning of . is lost when it is used inside a character class. Just like $, +, *, etc.
@Evert - Yeah, sorry, I wasn't as clear as I could've been when I mentioned not needing to escape it. Normally full-stop means "any character" so to actually match a literal full-stop you escape it as \., but as cdhowie said you don't need to escape it within the square brackets. (You can go ahead and escape it anyway and it should work the same, but you don't need to.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.