Luther-Varys
1/4/2017 - 11:29 PM

Create a regex expression in Javascript

Create a regex expression in Javascript


//http://stackoverflow.com/questions/31043039/javascript-string-match-pass-string-variable-in-regular-expression

function myFunction() {
    var str = "The rain in SPAIN stays mainly in the plain",
        test = "ain",
        re = new RegExp(test, 'gi'),
        res = str.match(re);

    console.log(res);
}


//http://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression
//***REMEMBER TO ESCAPE THE BACKSLASH WHEN CREATING A REGEX SYSNTAX
let regex_Bad:RegExp = new RegExp("(?:\d|\.|,)","g");    //Bad syntax \ not escaped
let regex_Good:RegExp = new RegExp("(?:\\d|\\.|,)","g"); //Good syntax \ escaped