将正则表达式传递给JQuery选择器 [英] Pass Regex To JQuery Selector
问题描述
我有以下情况. 我有正则表达式,但不能将其传递给jQuery选择器. 我正在尝试关注.
Hi I have following scenario. I have working regex but cant pass it to jQuery selectors. I am trying following.
$("#prefix_[\d]{1, 2}_postfix")
我的元素的ID如下 prefix_10_postfix prefix_1_postfix
My elements have ids as follows prefix_10_postfix prefix_1_postfix
请引导我.
推荐答案
您可以使用以-属性值选择器开头和结尾的
You can use starts with and ends with attribute-value selector
$('[id^="prefix_"][id$="_postfix"]')
这将选择所有ID以 prefix _ 开头并以 _postfix 结尾的元素.
This will select all the elements whose id starts with prefix_ and ends with _postfix.
如果页面包含许多元素,其ID以prefix_
开头并以_postfix
结束,但不符合在两个元素之间应为一或两个数字的条件,例如. <div id="prefix_tushar_postfix"></div>
,选择器的开头和结尾将不起作用.在这种情况下,filter
可以与属性选择器结合使用.
If the page contains many elements whose id starts with prefix_
and ends with _postfix
but doesn't match the criteria that in between them should be one or two numbers, ex. <div id="prefix_tushar_postfix"></div>
, the starts with and ends with selector will not work. In this case filter
can be used in combination with attribute selectors.
var regex = /^prefix_\d{1,2}_postfix$/;
// Narrow down elements by using attribute starts with and ends with selector
$('[id^="prefix_"][id$="_postfix"]').filter(function() {
// filter the elements that passes the regex pattern
return regex.test($(this).attr('id'));
}).css('color', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="prefix_1_postfix">prefix_1_postfix</div>
<div id="prefix_123_postfix">prefix_123_postfix</div>
<div id="prefix_tushar_postfix">prefix_tushar_postfix</div>
<div id="prefix__postfix">prefix__postfix</div>
<div id="prefix_11_postfix">prefix_11_postfix</div>
<div id="prefix_aa_postfix">prefix_aa_postfix</div>
这篇关于将正则表达式传递给JQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!