Alvin Alvin - 10 days ago 5
Javascript Question

Regex from loops

this.personRegex = (input) => {
return new RegExp(persons.map((person) => {
return person.fullname;
}).join("|"), "gi");
}


the above give me :

/lwe|alvin/gi;


How do I get the below:

/\b(?:lwe|alvin)\b/gi;

Answer

personRegex = (persons) => {
    return new RegExp(persons.map((person, i) => {
        if (i == 0) {
            return "\\b(?:" + person.fullname;
        }
        if (i == persons.length - 1) {
            return person.fullname + ")\\b";
        }
        return person.fullname;
    }).join("|"), "gi");
}

console.log(personRegex([{
    fullname: "lwe"
}, {
    fullname: "alvim"
}]));

or

you can simply do this

personRegex = (persons) => {
    return new RegExp("\\b(?:"+persons.map((person, i) => {
        return person.fullname;
    }).join("|") + ")\\b", "gi");
}

console.log(personRegex([{
    fullname: "lwe"
}, {
    fullname: "alvin"
}]));

Hope this helps :)