Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a Javascript match with a pattern that depends on a variable?

The current implementation of Remy Sharp's jQuery tag suggestion plugin only checks for matches at the beginning of a tag. For example, typing "Photoshop" will not return a tag named "Adobe Photoshop".

By default, the search is case-sensitive. I have slightly modified it to trim excess spaces and ignore case:

for (i = 0; i < tagsToSearch.length; i++) {
    if (tagsToSearch[i].toLowerCase().indexOf(jQuery.trim(currentTag.tag.toLowerCase())) === 0) {
        matches.push(tagsToSearch[i]);
    }
}

What I have tried to do is modify this again to be able to return "Adobe Photoshop" when the user types in "Photoshop". I have tried using match, but I can't seem to get it to work when a variable is present in the pattern:

for (i = 0; i < tagsToSearch.length; i++) {
    var ctag = jQuery.trim(currentTag.tag);
    if (tagsToSearch[i].match("/" + ctag + "/i")) { // this never matches, presumably because of the variable 'ctag'
        matches.push(tagsToSearch[i]);
    }
}

What is the correct syntax to perform a regex search in this manner?

like image 202
John Rasch Avatar asked May 14 '26 15:05

John Rasch


2 Answers

If you want to do regex dynamically in JavaScript, you have to use the RegExp object. I believe your code would look like this (haven't tested, not sure, but right general idea):

for (i = 0; i < tagsToSearch.length; i++) {
    var ctag = jQuery.trim(currentTag.tag);
    var regex = new RegExp(ctag, "i")
    if (tagsToSearch[i].match(regex)) {
        matches.push(tagsToSearch[i]);
    }
}
like image 70
Dan Lew Avatar answered May 16 '26 04:05

Dan Lew


Instead of

"/" + ctag + "/i"

Use

new RegExp(ctag, "i")
like image 45
KaptajnKold Avatar answered May 16 '26 04:05

KaptajnKold