使用RegExp动态创建正则表达式,并过滤内容
我正在努力使用 RegExp 对象来动态创建表达式并将其应用于一组元素。
这是一个jsFiddle,下面是代码:
<div id='selectors'><span>A-F</span><span>G-L</span><span>M-S</span><span>T-Z</span></div>
<a hreh=#>Astring</a>
<a hreh=#>Cstring</a>
<a hreh=#>Xstring</a>
<a hreh=#>Dstring</a>
<a hreh=#>Zstring</a>
$('div#selectors span').click(function(){
expression = "/^["+$(this).html()+"].*$/";
rx = RegExp(expression,'i');
console.log(rx,'expression');
$("a").each(function(){
if($(this).html().match(rx) !== null){
$(this).addClass('selected');
}
});
})
I am struggling with using the RegExp
object to allow me to dynamically create an expression, and apply it to a group of elements.
Here is a jsFiddle, below is the code:
<div id='selectors'><span>A-F</span><span>G-L</span><span>M-S</span><span>T-Z</span></div>
<a hreh=#>Astring</a>
<a hreh=#>Cstring</a>
<a hreh=#>Xstring</a>
<a hreh=#>Dstring</a>
<a hreh=#>Zstring</a>
$('div#selectors span').click(function(){
expression = "/^["+$(this).html()+"].*$/";
rx = RegExp(expression,'i');
console.log(rx,'expression');
$("a").each(function(){
if($(this).html().match(rx) !== null){
$(this).addClass('selected');
}
});
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JavaScript 自动在表达式的末尾和开头添加“/”。从字符串中删除它们,此处示例
JavaScript automatically adds "/" at the end and the beginning of the expression. Remove them from your string, Example Here