如何使用依赖于变量的模式执行Javascript匹配? [英] How do I perform a Javascript match with a pattern that depends on a variable?
问题描述
Remy Sharp的jQuery标签建议插件的当前实现仅检查标记开头的匹配项.例如,键入"Photoshop"将不会返回名为"Adobe Photoshop"的标签.
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]);
}
}
我试图做的是再次修改此内容,以便当用户键入"Photoshop"时能够返回"Adobe Photoshop".我尝试使用match
,但是当模式中存在变量时,我似乎无法使它工作:
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?
推荐答案
如果要在JavaScript中动态进行正则表达式,则必须使用
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]);
}
}
这篇关于如何使用依赖于变量的模式执行Javascript匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!