0

I'm trying to add a regular expression inside a JavaScript function. I've never done something like this before. How is this done? I've got the length part correct, but the regex has me stuck.

if(searchTerm('Ford GT')) {
    alert ('Query OK');
} else {

    alert ('Invalid query');
}


function searchTerm(query) {
    if( (query.length >= 2 && query.length <= 24) && (query.test('/^[a-z0-9()\- ]+$/i')) )  {
        return true;
    } else {
        return false;
    }
}
0

3 Answers 3

1

When using .test() the syntax is regex.test(string)

/^[a-z0-9()\- ]+$/i.test(query)
Sign up to request clarification or add additional context in comments.

Comments

0
function searchTerm(query) {
    var regex = /^[a-z0-9()\- ]{2,24}$/i;
    return regex.test(query);
}

1 Comment

Hi Marc. It's normally a good idea to add some commentary around the code in answers, if only so they don't get flagged up for review.
0

test is method of the RegExp Object (try console.log({}.toString.call(/\d/));), not of the String Object. Thats's why use the syntax regex.test(string). Also your function can be rewritten more compact:

function searchTerm(query) {
    return query.length >= 2 && query.length <= 24 && /^[-a-z\d() ]+$/i.test(query);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.