Reputation: 1926
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;
}
}
Upvotes: 0
Views: 58
Reputation:
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);
}
Upvotes: 0
Reputation: 966
function searchTerm(query) {
var regex = /^[a-z0-9()\- ]{2,24}$/i;
return regex.test(query);
}
Upvotes: 0