Barry Hamilton Barry Hamilton - 3 months ago 20
Javascript Question

jquery regex replace non numeric characters but allow plus

$('#target').val($('#target').val().replace(/[^\d]/g, ""));


I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.

How would I modify the regex to allow this?

Help much appreciated

Answer

Put - and + in the character class.

$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));