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

Is there any 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)")); // always returns the 1st newline (7)
alert(indexOfLastNewline(str)); // returns correctly (23)

Update

even if I use a RegExp object, I still get the same result

http://jsfiddle.net/yMMrk/2/

Answers


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.


Need Your Help

Dynamic Text Using JavaScript & PHP?

php javascript text dynamic submit

I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).

Most efficient way to delimit key

php string

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.