如何在jQuery中通过regex过滤有理数字的字符串数组

时间:2017-10-08 11:23:23

标签: jquery regex

有一个数组:

numberList = ["2.1", "4.1.1", "3.0.1", "5.2.1", "7.0.1", "8.1", "5.0.2"]

我想只过滤那些包含.0的数字我编写了一个正则表达式并在regex101进行了检查,并在那里工作。

\d\.0(\..*)?

之后,我通过下划线js编写了_.filter函数,并将过滤后的值存储到名为filteredList的新数组中。

var filteredList = _.filter(numberList, function(num){ return num.search(\d\.0(\..*)?) });

所以,输出应该是:

filteredList  = ["3.0.1", "7.0.1", "5.0.2"]

但是,我收到了错误。那里发生了什么错?



var numberList = ["2.1", "4.1.1", "3.0.1", "5.2.1", "7.0.1", "8.1", "5.0.2"];

var filteredList = _.filter(numberList, function(num){ return num.search(\d\.0(\..*)?) });

console.log(filteredList);

<script src="https://rawgit.com/jashkenas/underscore/master/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用此代码:

var numberList = [];
var options = $('#select_box');
$('#select_box option').each(function() {
    numberList.push($(this).text());
});

var re = /\d\.0/;
var filteredList = _.filter(numberList, function(num){ return re.test(num) });

console.log(filteredList);

Updated Fiddle