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

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

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

Solution 2:

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

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

console.log(validName("newName")) // should return TRUE
console.log(validName("newName32")) // should return TRUE
console.log(validName("_newName")) // should return TRUE
console.log(validName("4newName")) // should return FALSE
console.log(validName("new Name")) // should return FALSE
console.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.

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

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

Post a Comment for "Validating Property Names With RegEx"