JavaScript RegExp: Different results: Built pattern using string & using regexp “literal”?

前端 未结 2 881
时光取名叫无心
时光取名叫无心 2021-01-25 06:43

Is there any differences between using RegExp literals vs strings?

http://jsfiddle.net/yMMrk/

String.prototype.lastIndexOf = function(pattern) {
    patt         


        
2条回答
  •  醉梦人生
    2021-01-25 06:58

    Generally speaking, if you use a string to construct a regex, you need to escape backslashes; if you use a regex literal, you need to escape slashes if they occur in your regex.

    So the regex

    \s/
    

    can be written as a JavaScript string like this:

    "\\s/"
    

    and as a JavaScript regex literal like this:

    /\s\//
    

    Also, there is a difference in the handling of mode modifiers. For example, to make a regex case-insensitive, you can construct a regex object from a JavaScript string like this:

    var myre = new RegExp("[a-z]", "i");
    

    With a regex literal, you can do that directly:

    var myre = /[a-z]/i;
    

    Also, see this tutorial.

提交回复
热议问题