Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

51
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
            }
5 months 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');
}

5 months ago · Santiago Trujillo Report
Answer question
Find remote jobs