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?
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]);
}
}
Instead of
"/" + ctag + "/i"
Use
new RegExp(ctag, "i")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With