views:

1484

answers:

3

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?

+3  A: 

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]);
    }
}
Daniel Lew
+1  A: 

Instead of

"/" + ctag + "/i"

Use

new RegExp(ctag, "i")
KaptajnKold
A: 

You could also continue to use indexOf, just change your === 0 to >= 0:

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

But then again, I may be wrong.

Jordan S. Jones