How can I out if a string only contains a certain set of characters: {
A-Z
and }
?
For example
{VARIABLE}
=> should return true{VARiABLE}
=> should be false, because there's a lowercase i
inside{ VARIABLE}
=> should be false because there's a space etc.Oh, very important:
the string MUST have at least one character between {
and }
, so:
{}
should be false too...In that case use:
/^{[A-Z]+}$/.test(str);
The regexp represents any string of the format:
{
}
The ^...$
makes sure that the string should be exactly of this form, rather than a substring only (otherwise test{AAA}
would match too).
This sounds like a good case to use regular expressions. In particular, regexes allow one to match a range of characters - [A-Z{}]
would match any character which is either an uppercase letter, {
, or }
.
EDIT based on new requirements - you want to match something that starts with a literal {
, then has at least one character in the range A-Z
, then a closing }
. Which gives the regex:
{[A-Z]+}
Thus you could match against the entire regex:
val input = "{VARIABLE}"
return input.test(/{[A-Z]+}/) // returns true
"{VARiABLE}".test(/{[A-Z]+}/) // returns false
"{ VARIABLE}".test(/{[A-Z]+}/) // returns false
"".test(/{[A-Z]+}/) // returns false - open bracket didn't match
"{}".test(/{[A-Z]+}/) // returns false - A-Z part didn't match
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