This seems to be "hacking" for your question. But since you just want to know how it works, I think it's still be a good practise:
var re = /(\w+)\s(\w+)\s(\w+)\s(\w+)/;
var str = "mango apple banana orange";
var newstr = str.replace(re, "$2 $1 $3 $4");
console.log(newstr);//outputs apple mango banana orange, (how does it do this?)
\w: Matches alphabet character and numeric (a-z, A-Z and 0-9).
\w+: Matches with this pattern one or more times.
(\w+): Wrap this pattern in a group.
\s: Matches space
The first pattern (\w+) matches mango, the second pattern matches apple, same to the others...
Then, in the output, if you want to use the matched result inside each group, you can use:
"$2 $1 $3 $4"
$2: prints the matched result in group 2
$1: prints the matched result in group 1
$3: prints the matched result in group 3
$4: prints the matched result in group 4
$$ is used to insert a $ character to the result:
console.log('abc'.replace(/(a)(b)(c)/, '$1 $$ $2'));
In this example, we split abc to 3 groups. Group 1 contains a, group 2 contains b, group 3 contains c. Then, we replace 3 groups with group 1 value + $ character + group 2 value.
$` is used to insert a character which is getting before the matched string
console.log('abc'.replace(/b/, '$`'));
It matches b character, then getting a character to replace with b
$' is used to insert a character which is getting after the matched string
console.log('abc'.replace(/b/, "$'"));
It matches b character, then getting c character to replace with b
$& is used to insert the matched string. If not matched, it returns the default string.
console.log('abc'.replace(/(b)/, '$1 $&'));
console.log('abc'.replace(/x/, '$&'));
The way to use $n is as same as the way to use $1 $2 $3 and $4 above. We replace n with 1 2 3 4.