user1592380
user1592380

Reputation: 36317

Js: Continue if first statement fails

I'm using node and regex to search multiple text files for a specific piece of information which is present in each file but stored in different way in different files. There are several patterns I've found and I have the following function:

function findRegexInText(str, regex) {

let m;
let arr = [];

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
        if (match && match.length) {
            arr.push(match.trim());
        }
    });

}
let unique = [...new Set(arr)];

return arr[0];

}

In my main function I would like to call a series of searches:

       let code;

         code = findRegexInText(substr1, regex1);
         code = findRegexInText(substr2, regex2);
         code = findRegexInText(substr3, regex3);

I'd only like to run the second if the first expression comes up empty. and the third if the first 2 fail. What is the best way to do this in JS/Node?

Upvotes: 1

Views: 78

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

Use a function to iterate through an array of substrings and matches and returns the first non-empty result:

const searches = [
  [substr1, regex1],
  [substr2, regex2],
  [substr3, regex3],
];
const code = findMatch(searches);
const findMatch = (searches) => {
  for (const [substr, regex] of searches) {
    const result = findRegexInText(substr, regex);
    if (result) return result;
  }
};

Also consider using matchAll instead of the ugly while:

function findRegexInText(str, regex) {
    for (const m of (str.matchAll(regex) || [])) {
        for (const group of m) {
            if (group) {
                return group.trim();
            }
        }
    }
}

Upvotes: 1

Related Questions