RamAlx
RamAlx

Reputation: 7334

Value.replace in javascript for not allowing specific characters

I'm using a regular expression in javascript that allows only numbers and two kinds of separators "," or "." This regular expression is the following:

/^[0-9]+([,.][0-9]+)?$/g

Now, it's mandatory that if a user tries to enter a character or something else besides a number with , or . separator to prevent him. To be more specific if a user types 123asv I should display only the 123.

So i wrote this:

value.replace(/[0-9]+([,.][0-9]+)?$/g, '');  

But this is not allowing enter number. This is reasonable because i replace every value that matches the above regex with space. How to edit it so as to achieve the desired functionality?

Upvotes: 1

Views: 1224

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

In your current scenario, you need to remove any digits, , and . symbols from the input string, since you have extra code that validate/sanitizes extra comma/periods:

value = value.replace(/[^\d,.]+/g, '')

The [^\d,.]+ pattern matches 1 or more chars that are not digits, . and ,, and g modifier matches multiple occurrences. See this regex demo.

Note that in case there is no additional code to validate separators, you may add an alternative to remove all . and , but their last occurrences:

value = value.replace(/[^\d,.]+|[.,](?=.*[,.])/g, '')
                               ^^^^^^^^^^^^^^^ 

See this regex demo. The [.,](?=.*[,.]) matches a , or . that are followed with any 0+ chars other than line break chars and then another , or ., but only the first matched . or , are removed since the (?=...) lookahead is a non-consuming construct.

Then test if the value matches the number pattern:

if (value.test(/^[0-9]+([,.][0-9]+)?$/)) { ... }

Do not use the global modifier with the RegExp#test() method.

Upvotes: 1

Related Questions