Here's a typescript method that wants to walk through an array of strings, and return another array of strings, where, strings that match the regexp (formatted something like "[la la la]" will become just "la la la" and strings that don't match are dropped. So that if my input array is:
"[x]", "x", "[y]"
it becomes
"x", "y"
Here's my code:
questions(): string[] {
var regexp = /\[(.*)\]/;
return this.rawRecords[0].map((value) => {
console.log(value);
var match = regexp.exec(value);
if (match) {
return match[1];
}
});
}
I end up with output like this:
"x", undefined, "y"
because of the "if (match)". What's the right typescript/javascript way of writing this code?
Just filter
them out:
return this.rawRecords[0].map((value) => {
console.log(value);
var match = regexp.exec(value);
if (match) {
return match[1];
}
});
}).filter(x=>!!x);
What map does is to apply your function to each and every element in your list. Your function does not return any value when regex is not matched. So, probably JS makes it return undefined for that cases. If you wanna drop the ones that do not match regexp, you should use filter right away.
Think about names of functions and you will have a better understanding right away(map maps a function to a list and filter filters a list).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With