将Regex传递给JQuery Selector

嗨,我有以下情况。 我有正则表达式,但不能将它传递给jQuery选择器。 我正在努力追随。

$ $("#prefix_[\d]{1, 2}_postfix")

我的元素有如下前缀:prefix_10_postfix prefix_1_postfix

请指导我。

您可以使用start with和属性值选择器结束

 $('[id^="prefix_"][id$="_postfix"]') 

这将选择id以prefix_开头并以_postfix结尾的所有元素。


如果页面包含许多元素,其id以prefix_并以_postfix但与它们之间的标准不匹配,那么它们应该是一个或两个数字,例如。

,选择器的开头和结尾都不起作用。 在这种情况下, filter可以与属性选择器结合使用。

演示

 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'); 
  
prefix_1_postfix
prefix_123_postfix
prefix_tushar_postfix
prefix__postfix
prefix_11_postfix
prefix_aa_postfix