Search code examples
javascriptregexcasperjs

Failed to get expected output on building RegExp from a string


In casperjs(web scraping dependency), we can't pass RegExp object directly to web page context. So, I need to pass regexp as a string to the web page context and build the RegExp there.

var string = "(ABCD)"; 
var normalize = {
            regexp: '/(\()(\w*)(\))/g',
            newValue: '$2'
       }; 
var newString = string.replace(new RegExp(normalize.regexp), normalize.newValue); 
console.log(newString); -> It's printing "(ABCD)" instead of "ABCD"

Any suggestions where I am doing wrong to get the expected output of "ABCD"?


Solution

  • Since you can only use a string, define the pattern as a string (remember to escape each backslash to get a literal backslash in the regex) and build the RegExp object from the pattern:

    var normalize = {
                regexp: '(\\()(\\w*)(\\))',
                newValue: '$2'
           }; 
    var newString = string.replace(new RegExp(normalize.regexp, "g"), normalize.newValue); 
    

    The "g" modifier is declared in the RegExp constructor and not in the regexp string pattern (since JS regex does not support inline modifiers).