1

I have a code for CORS configuration in NodeJS. It is as follows:

var allowedOrigin = new RegExp('^https?://(' + config.get('http:allowedOrigins').join('|') + ')(:\\d+)?(/.*)?$');

It gives this error to

SyntaxError: Invalid regular expression: /^https?://(*.dev.examplewebsite.com|0.0.0.0|192.168.1.1|.*)(:\d+)?(/.*)?$/: Nothing to repeat
    at new RegExp (native)
    at Object.<anonymous> (/Users/yagiz/Desktop/example/project-api/src/lib/handlers/cors.js:4:21)
Yagiz
  • 1,033
  • 2
  • 21
  • 47
  • possible duplicate of [Is there a RegExp.escape function in Javascript?](http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) – Denys Séguret May 19 '15 at 17:22
  • I answered the asked question but I don't see how you could use such a regular exception. You probably need more sanitation. – Denys Séguret May 19 '15 at 17:28

1 Answers1

3

The problem here is that you need to escape the special characters (for example the dot) in the string you concatenate.

Find here a function to escape a string for a regular expression:

RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

var allowedOrigin = new RegExp(
    '^https?://(' +
    config.get('http:allowedOrigins').map(RegExp.escape).join('|') +
    ')(:\\d+)?(/.*)?$'
);
Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758