regex - JavaScript RegExp: Different results: Built pattern using string & using regexp "literal"? -


is there differences between using regexp literals vs strings?

http://jsfiddle.net/ymmrk/

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

http://jsfiddle.net/ymmrk/2/

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) 

you can test out here.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -