0

I came across this example in MDN documentation on using the replace method on strings.

This is the example cited there

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);//Smith,John

I changed the regex to the following and tested it.

var re = /(\w?)(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$1, $1");
newstr;//J, ohn Smith
var newstr1=str.replace(re,"$2, $1");
newstr1;//ohn, J Smith.

$1 must be J and $2 must be ohn Smith in this example. when I reversed the order of $n for newstr1,it should be 'ohn Smith, J`. but it is not.

is my understanding of $1 and $2 (substring matches correct) and why newstr1 is different?

Thanks for the comments

1 Answer 1

2

Actually, $1 is "J", $2 is "ohn" and the " Smith" is unmatched.

var re = /(\w?)(\w+)/,
    str = "John Smith";

str.replace(re, function (match, $1, $2) {
    console.log('match', match);
    console.log('$1', $1);
    console.log('$2', $2);
    return ''; // leave only unmatched
});
/* match John
   $1 J
   $2 ohn
   " Smith"
*/

Therefore, your swap is switching around the J with the ohn, giving you newstr1.

Why is this happening? because \w matches a word, but ? makes it optional, so just like (.*?)(.) captures one letter in $1, (\w?) is doing the same. The second capture, (\w+) can then only extend to the end of the word, dispite the +, because \w doesn't match whitespace \s.

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

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.