Skip to content Skip to sidebar Skip to footer

Validating Property Names With Regex

I'd like to quickly check if a string is valid to be used as a property name using the dot notation rules (any letters or numbers as well as _and $ as long as it doesn't start with

Solution 1:

Adding a negative lookahead should be good enough.

^(?![0-9])[a-zA-Z0-9$_]+$

Test

functionvalidName(str) {
  // check if str meets the requirements return/^(?![0-9])[a-zA-Z0-9$_]+$/.test(str);
}

console.log(validName("newName")) // should return TRUEconsole.log(validName("newName32")) // should return TRUEconsole.log(validName("_newName")) // should return TRUEconsole.log(validName("4newName")) // should return FALSEconsole.log(validName("new Name")) // should return FALSEconsole.log(validName("")) // should return FALSE

Solution 2:

Since \w covers [a-zA-Z0-9_] and \d covers [0-9] you could use this regex:

constvalidName = str => /^(?!\d)[\w$]+$/.test(str);

console.log(validName("newName")) // should return TRUEconsole.log(validName("newName32")) // should return TRUEconsole.log(validName("_newName")) // should return TRUEconsole.log(validName("4newName")) // should return FALSEconsole.log(validName("new Name")) // should return FALSEconsole.log(validName("")) // should return FALSE

Solution 3:

You can just make the first character of the pattern the same character set, except without including numbers:

^[a-zA-Z$_][a-zA-Z0-9$_]*$

Solution 4:

When solving regex like this I recommend using regexr.com

This snippet should take care of your issue.

functionvalidName(str){
    // check if str meets the requirementsreturn/^[^0-9][a-zA-Z0-9$_]+$/.test(str)
}

console.log(validName("newName"))   // TRUEconsole.log(validName("newName32")) // TRUEconsole.log(validName("_newName"))  // TRUEconsole.log(validName("4newName"))  // FALSEconsole.log(validName("new Name"))  // FALSEconsole.log(validName(""))          // FALSE

Post a Comment for "Validating Property Names With Regex"