Question:
My situation : I have an input masked like this: 0,0000 %
. However, to be able to validate as I want, I need to use a replace
, changing the comma to the period, removing the %
and then treating the value like this: 0.0000
.
I know I can use something like numero.replace(",",".")
but that will only replace the comma with the period, and my validation will keep failing.
Is it possible in a single replace
or similar code, change the characters and remove the %
?
Although the problem has already been solved, below is my answer to Sergio :
In my validation, I can only have numbers less than or equal to 100. As for the format (string or number), I cannot say with 100% certainty. I think it will have to be number , as this value will probably be stored in a BD and as a string I don't think it will be very viable.
Detail : It is not recommended that I use anything backend for now. Front-end only . It's more of a client side validation to not let the user send out bizarre values in the post.
Answer:
It is possible with regular expression. I'm not a master at the subject, but this seems to do the trick:
var re = /^(\d+),(\d+) %$/;
console.log("0,0000 %".replace(re, "$1.$2"));
The regular expression above works like this:
-
^
: from the beginning of the string -
(\d+)
: there must be one or more digits; the parentheses are to capture what to match that part of the expression -
,
: followed by a comma -
(\d+)
: followed by one or more digits (again captured) -
%
: followed by space and percent sign -
$
: end of string (ie nothing after percentage)
In the second part of replace
, the two groups captured with parentheses are referenced as $1
and $2
respectively. That is, $1
is the digits before the comma, and $2
is the digits after it. We assemble a new string with these two terms, and .
in the middle instead of ,
.
Considering your edit, this expression seems insufficient, as it allows for any number, even greater than 100 (except negatives, which you didn't mention but I'm considering invalid). A more precise expression:
/^(\d{1,2}|100),(\d+) %$/
The new part, (\d{1,2}|100)
, means that before the comma there must be any two digits, or the value "100"
.