Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for a real number with comma or dot for JavaScript

I want to know what I'm doing wrong in this code for checking a real number:

var regex = new RegExp(/([0-9]+[\.|,][0-9]*)|([0-9]*[\.|,][0-9]+)|([0-9]+)/g);
var invalid = this.value.match(regex);

The above doesn't work for me while the expression

([0-9]+[\.|,][0-9]*)|([0-9]*[\.|,][0-9]+)|([0-9]+) 

works in the tester.

like image 631
R01010010 Avatar asked Apr 11 '26 08:04

R01010010


1 Answers

Do

var regex = new RegExp("([0-9]+[.|,][0-9])|([0-9][.|,][0-9]+)|([0-9]+)/g);([0-9]+[.|,][0-9])|([0-9][.|,][0-9]+)|([0-9]+)", 'g');

or

var regex = /([0-9]+[.|,][0-9])|([0-9][.|,][0-9]+)|([0-9]+)/g​;

Two constructs are possible : new RegExp(string,'g') or /somestring/g. Don't mix them. In your case of a constant regexp, it will be more efficient to choose the second one because it is precompiled.

See the MDN documentation

like image 123
Denys Séguret Avatar answered Apr 12 '26 22:04

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!