JQuery grep, set with regex
I'll start this question by asserting that I am really bad with regex.
Said this, I wonder if it is possible to filter the array using jquery $ .grep, match strings with a specific string, something like this:
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var s = a.split(",");
var array = $.grep(s, function(x, y) {
return ??????;
});
so after applying $ .grep or any other function that might help, I need the number after the :: number with ABC, so my new array would be:
array[12, 2];
Any help with this ??? I would be very grateful!
+3
source to share
2 answers
$.grep
select only the array elements that satisfy the filter function.
You need an extra step for $.map
all numbers from the grepped array.
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var b = $.grep(a, function(item) {
return item.indexOf("ABC:") >= 0;
});
var array = $.map(b, function(item) {
return item.split(":").pop();
});
+2
source to share
Try
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
// map array ,
// test array items for "ABC" string ,
// filter `Number` in strings containing "ABC" ,
// return filtered Numbers , in newly mapped array
var s = $.map(a, function(n) {
return (/ABC/.test(n) ? Number(n.split(":").filter(Number)) : null)
}); // [12, 2]
+1
source to share