regex - JavaScript RegExp: Different results: Built pattern using string & using regexp "literal"? -
is there differences between using regexp literals vs strings?
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 1st newline (7) alert(indexoflastnewline(str)); // returns correctly (23)
update
even if use regexp
object, still same result
you need escape \
in string version \\
, 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)
Comments
Post a Comment