1

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/

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.