I am trying to write a regular expression to check for the following characters: ( ) { } [ ]
The following code takes what the user has entered and console logs a message depending on whether they have entered an invalid character. The problem I am having is that I cannot get it to check for both [ ] characters - the code below checks for [ but not ]
var nameString = $("#name").val();
var regexp = /[(){}[]/;
var invalidCharacters = nameString.match(regexp);
if(invalidCharacters){
console.log('Contains invalid character');
} else{
console.log('DOES NOT contain an invalid character');
}
How do I add ] and keep the regex valid?
You must place the ] in the beginning, like so,
var regexp = /[](){}[]/;
Now, understandably, this looks weird. It looks like an empty character class, [], followed by pairs of brackets, (), {}, and []. But believe it or not, it's actually the standard in regular expressions to disregard the ] as indicating the end of a character class if it's the first character present. Therefore the above is actually a character class for the characters ](){}[.
You might also rearrange that as ][(){}, but the regex still looks confusing:
var regexp = /[][(){}]/;
See, now it looks like two character classes—an empty one, and another for the characters (){}—but again, that's just what it looks like, and the above actually works too—it's the set of characters ][(){}.
The thing is, most people don't know about this aspect of character classes, and so you'll only end up confusing others who read your code. I recommend simply escaping the ], as @vks answers:
var regexp = /[(){}[\]]/;
This will be understood by all.
[[\]({})]
You need to escape one of them so that another bracket range does not appear [ and ].
It should not form [[]==>this creates problem.use [[\] now its fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With