In the regex below,
var res = new RegExp('(\\s|^)' + foo).test(moo);
You are constructing the regular expression by passing a string to the RegExp constructor.
You need to escape the
\ so that your string literal can express it as data before you transform it into a regular expression.