RegExp#exec
and String#match
JS-D007 1const convertDuration = (str) => {
2 const regex = /\d{1,2}/g;
3
4 return str.match(regex).join(':'); 5};
6
7const convertPublishedTime = str => (
RegExp#exec
and String#match
should only be used when we need to use the parts of a string that match a specific pattern:
const matches = /[a-zA-Z0-9]+/.exec(string)
for (const match of matches) {
processMatch(match)
}
If you only want to know whether a string matches a particular pattern, RegExp#test
is a faster alternative.
const matches = str.match(/[a-zA-Z0-9]/) ? process(str) : process("default-str");
const strMatchesPattern = !!str.match(/regex/)
const regexp = new RegExp("[a-zA-Z0-9]*")
if (regexp.exec(myString)) {
// ...
}
const matches = '/hasTheMagic/'.test(str) ? process(str) : process("default-str");
const strMatchesPattern = /regex/.test(str)
const regexp = new RegExp("[a-zA-Z0-9]*")
if (regexp.test(myString)) {
// ...
}