javascriptregexcoffeescripthubot

Hubot not responding to regex variable


I've been playing around with Hubot for a bit, far too long actually but I'm getting stuck at matching a string in an array. replies is an array with some replies.

So this works:

module.exports = (robot) ->
    robot.hear /seb/i, (msg) ->
    msg.send msg.random replies

However, this does not:

regex = new RegExp triggers.join(), 'gi'

module.exports = (robot) ->
    robot.hear regex, (msg) ->
    msg.send msg.random replies

regex is a string made up of the contents of an array of strings. In this case printing out regex returns "/seb/i".

Anyone care to explain? I never was a big fan of JavaScript and Coffeescript :)


Solution

  • Array.prototype.join takes a string parameter as separator. It defaults to , when no parameter is given.

    Let's assume we have the following array of keywords:

    const triggers = ["kw1", "kw2", "kw3"]
    

    Calling triggers.join() will return the string kw1,kw2,kw3. Passing that to RegExp constructor will create a RegExp object that matches the exact string kw1,kw2,kw3 (also ignores case because of the i flag).

    In order to match multiple keywords with a regex, you must separate them with special-or (|) operator.

    So instead of

    regex = new RegExp triggers.join(), 'gi'
    

    You should write

    regex = new RegExp triggers.join('|'), 'i'
    

    You might also want to drop the g (global search) flag as well, since it's enough to match the first occurrence of a keyword in your case.