The apparent objective is to detect the first character, but I see a fundamental problem, and it is to detect the names of the variables.
For this, what I do is, besides looking at the first character, to see that the second is not a number, and also accept other characters such as underscore and weights sign.
These characters are the most common, but at the time of testing, you can accept up to unicode characters. I will not go into that since it is complicated, but I leave an approximate solution.
A variable can not start with a number, and the following can be a number, letters, or whatever, as long as it does not come up against the special characters of the language.
- So that the first character of the variable is not a number:
[^0-9]
- To make it a letter:
[a-z]
- A number:
\d
- One point:
\.
... Here you have to be careful, because the point in some languages is like a wild card, that is, accepts anything.
- Pad (for this character there is no trick):
#
.
var nombre_variable="[^0-9][a-z\d_$]{0,}"
new RegExp(nombre_variable,"i")
var almohadilla=new RegExp("^#"+nombre_variable+"$")
var propiedad=new RegExp("^\."+nombre_variable+"$")
console.log(almohadilla)
console.log(propiedad)
var pruebas=[
"variable_8", "3_a"
]
for(var i in pruebas){
console.log( "."+pruebas[i]+" "+
propiedad.test("."+pruebas[i])
)
console.log( "#"+pruebas[i]+" "+
propiedad.test("#"+pruebas[i])
)
}