如何使用依赖于变量的模式执行 Javascript 匹配?
Remy Sharp 的 jQuery 标签建议插件的当前实现仅检查匹配标签的开头。 例如,输入“Photoshop”将不会返回名为“Adobe Photoshop”的标签。
默认情况下,搜索区分大小写。 我稍微修改了它以修剪多余的空格并忽略大小写:
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
,但当模式中存在变量时,我似乎无法让它工作:
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]);
}
}
以这种方式执行正则表达式搜索的正确语法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想在 JavaScript 中动态执行正则表达式,则必须使用 RegExp 对象< /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):
代替
使用
Instead of
Use
您也可以继续使用indexOf,只需将=== 0更改为>= 0:
但话又说回来,我可能是错的。
You could also continue to use indexOf, just change your === 0 to >= 0:
But then again, I may be wrong.