正则表达式:匹配部分或完整字符串
我有一个小脚本,它从文本输入中获取值,并且需要部分或完全匹配数组中的项目。
我现在正在努力解决正则表达式和语法问题,想知道我是否可以请教您。
for (var i=0; i < liveFilterData.length; i+=1) {
if (liveFilterData[i].match(liveFilter.val())) {
alert();
}
}
我需要 liveFilter.val() 和正则表达式来匹配当前数组项 liveFilterData[i],因此如果有人在文本框中输入 H 或 h,它会检查数组中是否有匹配项。如果他们输入 He 或 he,那么它会匹配 Head、Header 或 header。
抱歉,我在网上查找了有关如何构建正则表达式的信息,但我无法解决。
I have small script that takes the value from a text input and needs to match an item in an array either partially or fully.
I'm struggling at the moment with the regular expression and the syntax and wondered if I could pick your brains.
for (var i=0; i < liveFilterData.length; i+=1) {
if (liveFilterData[i].match(liveFilter.val())) {
alert();
}
}
I need the liveFilter.val() and Regular Expression to match the current array item liveFilterData[i] so if someone types in H or h in the text box, it checks if there is a matching item in the array. If they type in He or he then it matches Head, Header or heading.
Sorry, I've looked all over the web on how to build regular expressions but I can't work it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的字符串比较应该可以解决问题:
liveFilterData 应该包含小写的单词。
Simple string comparison shold do the trick:
liveFilterData should contain the words in lower case.
我不确定我完全理解这个问题。 liveFilter.val() 是正则表达式,还是只是您尝试与数组中的任何值进行匹配的字符串?我猜测您在文本框的按键、按键或按键上有一个事件,并且您上面编写的代码在该事件的回调中运行。如果是这样,您可以执行多种操作来将该值转换为适当的正则表达式:
"^"+liveFilter.val()
,由于您在循环中使用正则表达式,因此您应该使用new RegExp
对其进行预编译,因此您的循环将类似于:希望这会有所帮助!
I'm not sure I totally understand the question. Is
liveFilter.val()
a regular expression, or is it just a string that you are trying to match against any value in an array? I'm guessing that you have a event on the textbox's keypress, keydown or keypress, and that the code you wrote above runs in the callback to this event. If so, there are a number of things you can do to convert the value to an appropriate regex:"^"+liveFilter.val()
, Since you are using the regex in a loop, you should precompile it withnew RegExp
, so your loop would look something like:Hope this helps!