Is it possible to combine a map
and a filter
in a single javascript expression? For example, I am currently doing the following to trim whitespace and remove empty results:
const s = "123 hiu 234234"
console.log(s
.split(/\d /g)
.filter((item, i) => item.trim())
.map((item, i) => item.trim())
);
Is there a more compact way to do that? And, as a follow up question, is the /g
necessary when doing split
or does that automatically split every occurrence?
CodePudding user response:
that...
const s = "123 hiu 234234"
console.log( s.match(/[a-z] /ig) )
CodePudding user response:
If a single word comes between the numbers, I think a single regular expression would be enough here - just match non-whitespace, non-digits:
const s = "123 hiu 234234"
console.log(s
.match(/[^\d ] /g)
);
CodePudding user response:
One way to do it would also be to define a function that takes two arguments that you can call which does the task. For example:
const s = "123 hiu 234234"
const Trim = (item, i) => item.trim();
console.log(s.split(/\d /).filter(Trim).map(Trim));
Or you could put the burden on the regex itself, for example only matching letters:
s="123 hiu 234234"
console.log(s.match(/[a-zA-Z] /g));
// /[a-z] /gi alternately