1

See http://jsfiddle.net/aEEUN/

why when I use backreference vs no backrefences, I get different results?

var str = "Hello World\nHello          ";
document.write("Without backreference: <br />");
var match = str.match(/\S(?![\s\S]*\S)/);
document.write("- match.index: " + match.index + "<br />"); // index is 16 

document.write("With backreference: <br />");
var match = str.match(/(\S)(?![\s\S]*\1)/);
document.write("- match.index: " + match.index); // index is 6
0

2 Answers 2

5

The difference is that you constrain the two character to be exactly the same.

In the first regular expression there must not be any non-whitespace character following:

/\S(?![\s\S]*\S)/

This basically means to match any non-whitespace character that is not followed by any other non-whitespace character. That’s why it matches the last o that is only followed by whitespace:

"Hello World\nHello          "
                  ^ no other non-whitespace character following

But in the second regular expression there must not be that specific character following that was matched before:

/(\S)(?![\s\S]*\1)/

This basically means to match any non-whitespace character that does not appear again in the rest of the string. That’s why the W is matched as it’s the first non-whitespace character that does not appear again after the first occurrence:

"Hello World\nHello          "
       ^ no other “W” following

That’s why it’s called a backreference: You reference a previously matched string.

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

Comments

0

That is some weird regex. The character class [\s\S] matches everything doesn't it? A space or non-space? Not sure exactly, but the \1 in the latter example has to refer to the same character that it did at the start (not just any non-space again)... which would give it a different result.

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.