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".
Remy Sharp的jQuery标签建议插件的当前实现仅检查标签开头的匹配。例如,键入“Photoshop”将不会返回名为“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:
我试图做的是再次修改它,以便当用户键入“Photoshop”时能够返回“Adobe Photoshop”。我尝试过使用匹配,但是当模式中存在变量时,我似乎无法使其工作:
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 个解决方案
#1
5
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):
如果要在JavaScript中动态执行regex,则必须使用RegExp对象。我相信你的代码看起来像这样(没有测试,不确定,但正确的一般想法):
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]);
}
}
#2
2
Instead of
代替
"/" + ctag + "/i"
Use
使用
new RegExp(ctag, "i")
#3
0
You could also continue to use indexOf, just change your === 0 to >= 0:
您还可以继续使用indexOf,只需将=== 0更改为> = 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.
但话说回来,我可能错了。
#1
5
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):
如果要在JavaScript中动态执行regex,则必须使用RegExp对象。我相信你的代码看起来像这样(没有测试,不确定,但正确的一般想法):
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]);
}
}
#2
2
Instead of
代替
"/" + ctag + "/i"
Use
使用
new RegExp(ctag, "i")
#3
0
You could also continue to use indexOf, just change your === 0 to >= 0:
您还可以继续使用indexOf,只需将=== 0更改为> = 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.
但话说回来,我可能错了。