Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
Variable validation according to javascript rules using RegEx

Is there any ways of improving this code?

I want variables that doesn't start with numbers and doesn't include special characters, such as (!@#$%^) When I join these RegEx patterns it does not work properly when variable includes special characters

            let text = prompt('add variable name');
            let pattern = /^[^0-9]/g;                    // check if it starts with number
            let condition = pattern.test(text);

            if (condition == true) {
                pattern = /[^a-zA-Z0-9$_]/;                //check if it contains special characters (!@#$%^*) except ($ , _)
                condition = pattern.test(text);
                if (condition == false) {
                    console.log("Variable name is Valid");
                }
                else {
                    console.log('Variable name Is Not Valid');  //includes special character
                }
            }
            else {
                console.log('Variable name Is Not Valid'); //starts with number
            }
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Using condition is already a boolean, so you can use if (condition)

You might rewrite your code using a pattern that checks that the string does not start with a digit, and in the character class specify all allowed characters and match until the end of the string $

In this case you can shorten the ranges to word characters \w and the dollar sign $

let text = prompt('add variable name');
let pattern = /^(?!\d)[\w$]+$/;
let condition = pattern.test(text);

if (condition) {
  console.log("Variable name is Valid");
} else {
  console.log('Variable name Is Not Valid');
}

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda