34

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.

1
  • 2
    It returns null because you have a 1 in the string so it does not match. Changing it to a valid string returns that string. jsfiddle.net/GLVAj Dec 29, 2011 at 4:05

3 Answers 3

54

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.');
}
1
  • 2
    I was putting the regex pattern inside single quotes and that was my issue... :D) Jan 4, 2015 at 15:16
16

Regex must be surrounded with /, not ', so that JavaScript creates a variable of type regex, not of type string. So for instance, for your ALPHA case, you should have

regex = /^[a-zA-Z]+$/;

See MDN's page on .match for more information about using .match.

0
1

Your code looks like it's inside a function { ... }. Are you returning anything? If not, that's why you're getting null back...

Also, regexes are surrounded by slashes (/.../), not quotes.

2
  • I have fixed the code up now, I meant that value.match(regex) was returning null. Not the function.
    – MichaelH
    Dec 29, 2011 at 4:00
  • The value returned from a function that doesn't return anything is undefined, not null. Apr 16, 2017 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.