Crea una funci贸n que reciba una expresi贸n matem谩tica (String) y compruebe si es correcta. Retornar谩 true o false.
- Para que una expresi贸n matem谩tica sea correcta debe poseer un n煤mero, una operaci贸n y otro n煤mero separados por espacios. Tantos n煤meros y operaciones como queramos.
- N煤meros positivos, negativos, enteros o decimales.
- Operaciones soportadas: + - * / %
Ejemplos:
"5 + 6 / 7 - 4" -> true
"5 a 6" -> falseconst isMathExpresion = (str) => {
str = str.replace(/\s+/g, ' ').split(' ').join('');
const regex = /^(\d+[\\+\-\\*\\/%]?)+\d+$/;
return regex.test(str);
};- First, I declare a function named
isMathExpresionthat receives a parameter namedstr.
const isMathExpresion = (str) => {- Then, I replace all the spaces in the
strparameter with a single space.
str = str.replace(/\s+/g, ' ');- Then, I split the
strparameter by spaces and join the resulting array into a string.
str = str.replace(/\s+/g, ' ').split(' ').join('');- Then, I declare a variable named
regexthat will store a regular expression that will be used to test if thestrparameter is a valid mathematical expression.
const regex = /^(\d+[\\+\-\\*\\/%]?)+\d+$/;-
The regular expression stored in the
regexvariable will match the following:^: The beginning of the string.(: The beginning of a capturing group.\d+: One or more digits.[\\+\-\\*\\/%]?: An optional+,-,*,/or%character.): The end of the capturing group.+: One or more times.\d+: One or more digits.$: The end of the string.
-
Then, I return the result of testing if the
strparameter matches the regular expression stored in theregexvariable.
return regex.test(str);
};- The
testmethod of theRegExpobject receives a string as a parameter and returnstrueif the string matches the regular expression, orfalseotherwise.