Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!