Search code examples
javascriptregexstringparentheses

js regexp variable parenthesis


So I have a function that receives an argument (namedc), then I create a regular expression like so: regC = new RegExp(c,'gi'). Now this works fine for most characters, but my function can also receive a ( or other paretheses. This cases create an error. I tried this: regC = '/['+c+']/gi', but it didn't work


Solution

  • Pass the character set '['+c+']' to RegExp functions as

    regC = new RegExp('['+c+']','gi');
    

    Because

    regC = '/['+c+']/gi'
    

    Makes a string