简体   繁体   中英

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 a number) as obviously if bracket notation is used then everything is valid.

I've been trying to figure out a regEx solution but my knowledge of regEx is not great. I think that my current pattern will allow letters, numbers, $ and _ but I don't know how to disallow starting with a number

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

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

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 

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 

您可以将模式的第一个字符设为相同的字符集,但不包括数字:

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM