I am trying to do something I thought would be pretty easy to do, which is to restrict a string to certain characters by matching a regular expression.
var value = 'FailureStr1ng'; var type = 'ALPHA'; var regex = null; switch(type) { case 'ALPHA': regex = '^[a-zA-Z]+$'; break; case 'NUMERIC': regex = '^[0-9]+$'; break; case 'ALPHANUMERIC': regex = '^[a-zA-Z0-9]+$'; break; } return value.match(regex);
For some reason, when using the match it always returns null
. Is there a way to fix this, or a better method to do this?
Note: The code here is a snippet of much larger code, and in turn the value and type variable are usually defined by another method.
The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.
An empty regular expression matches everything.
match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
You want RegExp.test
, which tests a value for a match instead of retrieving the match. With your existing code, that would mean:
if(!new RegExp(regex).test(value)){ alert('Your string was invalid.'); }
However, it would be preferable to use RegExp literals instead of strings, as they're much more efficient and clear, and less prone to error:
var value = 'FailureStr1ng'; var type = 'ALPHA'; var regex = null; switch(type) { case 'ALPHA': regex = /^[a-zA-Z]+$/; break; case 'NUMERIC': regex = /^[0-9]+$/; break; case 'ALPHANUMERIC': regex = /^[a-zA-Z0-9]+$/; break; } if(!regex.test(value)) { alert('Your string was invalid.'); }
Even better, use a dictionary:
var expressions = { ALPHA: /^[a-zA-Z]+$/, NUMERIC: /^[0-9]+$/, ALPHANUMERIC: /^[a-zA-Z0-9]+$/ }; if(!expressions[type].test(value)) { alert('Your string was invalid.'); }
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