2
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;
Alvin
  • 8,219
  • 25
  • 96
  • 177
  • As the additional stuff does not seem to be related to the number of persons, simply do it in the code **Regex("\b(?:"+ map() + ")\b")**. – Tobi Nov 24 '16 at 06:50
  • By adding `\b` to the beginning and end of the regexp you are creating? –  Nov 28 '16 at 05:46

4 Answers4

1

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

console.log(personRegex([{
    fullname: "lwe"
}, {
    fullname: "alvin"
}]));
Mr.7
  • 2,292
  • 1
  • 20
  • 33
1

You can simply do string concatenation:

var personAlternatives = persons.map((person) => { return person.fullname; }).join("|")
this.personRegex = (input) => {
    return new RegExp('\\b(?:' + personAlternatives + ')\\b', "gi");
}
knittl
  • 246,190
  • 53
  • 318
  • 364
1

This should give you the least overhead:

function buildRegex(array){
  var reg;
  var mapResult = array.map((item) => {
    return item.attr;
  }).join("|");
  return new RegExp("\\b(?:"+mapResult+")\\b", "gi");
}

console.log(buildRegex([{attr:"a"},{attr:"b"}]));
Tobi
  • 525
  • 4
  • 7
0

You can use template strings, with String.raw to avoid worrying about double backslashes:

personRegex = input => 
  new RegExp(
    String.raw`\b(?:${input.map(person => person.fullname).join("|")})\b`,
    "gi");

console.log(personRegex([{fullname: 'Bob'}, {fullname: 'Sally'}]));

In the real world, you would want to escape any possible special regexp characters in the input. For more information on doing that, see this question.

Community
  • 1
  • 1