Why does a javascript RegExp created by /…/ work but the same created via “new RegExp” does not?

前端 未结 3 571
情歌与酒
情歌与酒 2021-01-20 05:10

I\'m confused as to what the difference here is and why one works and the other does not. Can someone explain this?

//The string to search through
var str =          


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-20 05:31

    \ is the escape characters in strings. Hence, to create a literal backslash as escape character for the regular expressions, you need to escape it itself:

    var regEx = new RegExp("(/\\*)", "g" );
    

    If you use Chrome or Safari (maybe also in Firebug), you can easily see the resulting expression by executing the code in the console:

    > new RegExp( "(/\*)", "g" );
    /(/*)/g

    > new RegExp( "(/\\*)", "g" );
    /(/\*)/g

    P.S.: No need to escape the slash in the string (though it might be ignored in the regex).

提交回复
热议问题