-1

I have a text input field, where I am checking each click, so the user should enter only numbers. I need to do it with javascript.

I created this in my function:

 result = number.replace(/\D/g, '');return result;

I also tried result = number.replace(/[^0-9.\-]/g, '');return result;

This is working, so it doesn't allow to enter anything except numbers, BUT if I press any letter twice (gg or aa,...) then one of the letters is showing in input field.

If I enter different letters (ab, gh,...), then it is ok, it doesn't allow any letter. It happens only if I press the same letter twice.

Not sure why it is happening, as the regexp should allow only numbers.

Darksymphony
  • 2,155
  • 30
  • 54

1 Answers1

0

You need to use lowercase d to matching digits instead of capital D. Also to match whole number use + sign after d like \d+.

here is regex cheat sheet : https://www.rexegg.com/regex-quickstart.html

and you can use that link to simulate your regex : https://regexr.com/

Eren AY
  • 38
  • 5
  • if I use lowercase d+, then it replaces digits, I need to keep the digits. This number.replace(/\d/g, ''); will replace digits for nothing. So using capital D is ok in my case. The problem is just when I press 2 same letters – Darksymphony Apr 18 '19 at 10:17
  • I've just tried that and its output is : 12344, **var res = "bbb123aa44".replace(new RegExp(/\D+/g), '');** – Eren AY Apr 18 '19 at 10:44
  • yes, because you use uppercase D, not lowercase as you suggested. With D it works, but I think I found the issue with duplicate letters. I tried to return parseFloat(result) and now it is working as expected. – Darksymphony Apr 18 '19 at 11:03