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

前端 未结 2 907
时光取名叫无心
时光取名叫无心 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 07:17

    You need to escape your \ in the string version as \\, like this:

    String.prototype.lastIndexOf = function(pattern) {
        pattern = pattern + "(?![\\s\\S]*" + pattern + ")";
        var match = this.match(pattern);
        return (match == null) ? -1 : match.index;
    }
    
    function indexOfLastNewline(str) {
        var match = str.match(/\r?\n(?![\s\S]*(\r?\n))/);
        return (match == null) ? -1 : match.index;
    }
    
    var str = "Hello 1\nHello 2\nHello 3\nHello4";
    alert(str.lastIndexOf("(\\r?\\n)")); // returns correctly (23)
    alert(indexOfLastNewline(str)); // returns correctly (23)
    

    You can test it out here.

提交回复
热议问题