JavaScript

JavaScript

Made by DeepSource

Bad usage of RegExp#exec and String#match JS-D007

Performance
Major

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.

Bad Practice

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)) {
  // ...
}

Recommended

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)) {
  // ...
}