This code
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1")
and this code
var re = /(.+)\s(.+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1")
does exactly the same thing.
Are there any key differences between . (dot) and \w metacharacters?
.matches any non-newline character.\wmatches a word character, i.e. is equivalent to[A-Za-z0-9_].Using
\wmight seem the right way to go, but can go a bit wrong when dealing with names, as can be seen here:See also: