Monday, 15 March 2010

String.replace method in javascript using regex -


I came to this example using strings on the replacement method.

This example is quoted there

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

I changed regex into the following and tested it.

  var re = / (\ w?) (\ W +) /; Var str = "John Smith"; Var newstr = str.replace (again, "$ 1, $ 1"); Newstr; // J, Oh Smith var newstr1 = str.replace (again, "$ 2, $ 1"); Newstr1; // Oh, J Smith should be $ 1  J  and $ 2 should be  ohn smith  in this example When I reverse the order of newstr1 for $ 1, then it should be 'Ohhan Smith, J' but it's not.  

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

Thanks for the comments , $ 1 is "J" , $ 2 < / Code>

"ohn" and "smith" is unrivaled.

  var re = / (\ w?) (\ W +) /, Str = "John Smith"; ('$ 1', $ 1); Console.log ('$ 2', $ 2); Return ''; // Simply leave unmatched}); / * Match John $ 1 J $ 2 Ohanna "Smith" * /   

Therefore, your swap with j with oh Switching, give you newstr1 .

Why is this happening? Because \ w matches , but ? makes this optional, so as in (. *?) (.) Captures one letter in $ 1 , (\ W?) is doing the second capture, (\ w +) can only extend to the end of the word, despite + , because \ W does not match whitepaper \ s .

No comments:

Post a Comment