-2

I'm writing a JavaScript code like this:

var regex = new RegExp(["^",skill,"$"].join(""),"i");

When skill = 'c++', it reports an error "SyntaxError: Invalid regular expression: /^c++$/".

Any advice on how to write the regex in the correct way to take care of characters like "+"?

j08691
  • 204,283
  • 31
  • 260
  • 272
rxie
  • 79
  • 1
  • 5
  • There are many, many questions covering this problem, use the site search. – Etheryte Dec 17 '14 at 20:28
  • http://stackoverflow.com/a/2593661/251311 + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions – zerkms Dec 17 '14 at 20:29
  • escape the "+" sign with a backslash http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – Christine Dec 17 '14 at 20:30
  • Amusingly, `/^c++$/` is actually a valid regex in PCRE engines, such as PHP. JavaScript lacks several useful features like this one, and lookbehinds... – Niet the Dark Absol Dec 17 '14 at 20:34
  • Seems like you might be over-engineering to use a regex like this. Why not just `skill === 'c++'`? – FishBasketGordo Dec 17 '14 at 20:39

1 Answers1

0

You must escape any special regex characters from the "skill" string.

var escapedSkill = skill.replace(/(\W)/g, '\\$1');
var regex = new RegExp('^' + escapedSkill + '$', 'i');
regex; // => /^c\+\+$/i
maerics
  • 151,642
  • 46
  • 269
  • 291