0

I am trying to create an angular directive to be used with HTML inputs to filter out none numeric characters

Here is my regex I am using to achieve that:

inputValue.replace(/[^0-9\-\.]/g, "").replace(/\.(\.)/g, '$1');

However this regex does not cover these cases:

  • --5
  • 5.5.6
  • -5-5
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
SMH
  • 889
  • 3
  • 11
  • 30
  • Possible duplicate of [Regex - Match whole string](https://stackoverflow.com/questions/6298566/regex-match-whole-string) – revo Apr 30 '18 at 09:48

2 Answers2

0

If I'm not wrong, this is really simple.^^

\d

\d machtes every digit from [0-9]. You can test our RegEx very simple at https://regex101.com without writing any javascript code to test it.

Edit:

You might want to add a * to the \d.

\d*

The * is the greedy selector, which selects all of the type before.

0

In your regex you use a negated character class [^0-9\-\.] which matches not a digit 0-9, a - and a . so you are keeping those matches.

If you want to match anything but a number you could use [^0-9] or \D to match any character that is not a digit and replace that with an empty value.

let inputValue = `--5
5.5.6
-5-5
!@#$%# $%@% $%435 452545`;
inputValue = inputValue.replace(/\D/g, "");
console.log(inputValue);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70