1

I'm trying to learn to use $$, $&, $`,$',$n in my replace function. I am looking for some examples like this:

var re = /(\w+)\s(\w+)/;
var str = "mango apple banana orange";
var newstr = str.replace(re, "$2 $1");
console.log(newstr);//outputs apple mango banana orange, (how does it do this?)
Can anyone provide me with some examples and explanation on the use of each of these? I found out about them here and trying to understand. Thank you so much.

1 Answer 1

4

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.

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

2 Comments

Thank you very much for your answer. Can you also give some examples using $$, $&, $`,$',$n?
Thank you. This makes more sense now.

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.