Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda