Replacement strings with dollar signs

Tell us what’s happening:
I don’t understand what the dollar sign does? Can someone give me another example because the example that is given doesn’t make any sense to me.
Why are we using a capture group when they are used to look for repeat substrings?

Your code so far

let str = "one two three";
let fixRegex = /(\w+)\s(\w+)\s(\w+)/; // Change this line
let replaceText = ""; // Change this line
let result = str.replace(fixRegex, replaceText);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36.

Challenge: Use Capture Groups to Search and Replace

Link to the challenge:

The dollar sign$ in regex means the end or the beginning of a string. So it means to stop when the $ is in the end or to start from a particular letter if the $ is on the front.

But then in the answer, it has you use
let replaceText="$3 $2 $1"
can you explain what that means in this code? How does the number ‘3’ translate to the string ‘three’?

do you mean like this?

let first_last = "Bob Smith";
let r = /([a-z]+)\s([a-z]+)/i;
let last_first = first_last.replace(r, "$2, $1");
console.log(last_first); // Smith, Bob

the dollar sign plus number symbols are placeholders, and refer back to the capture groups, so $1 will refer to the first capture group, and $2 to the second capture group, they can be used to take parts of the original string and still keep them but maybe add something, or move them around


Yes, that makes sense to me. Thanks!

Do you know why we are using the \w instead of using the something such as [a-z] if we are searching through just strings?

If you use \w you are typing less, and it includes all word characters (it’s equal to [a-zA-Z0-9_])
it depends on what you need to do. In the case of this challenge both \w and [a-z] give the same result so it doesn’t matter.

1 Like

Coming back to the ‘+’ again… Why is it necessary to use the + with \w if we are just looking for strings of letters as opposed to multiple repeats of the strings?

if you use [a-z] that is one letter, but if you want to capture one word, it is (or can be) more than one letter, so you use the + to say “match one or more letters, matching as much as possible”

Can you help me clarify then, the difference between the “.” and +
I thought that the + was looking for multiple of the same thing and the . was just including whatever comes after the matched element.

the . symbol will match a single character, it is a jolly, it will match anything, but still only one character.

the + is an other thing altogether, it will say that the last thing before it instead of being matched only one time, it can be matched once or more

so if you have /a/ it will just match a single “a”. if you have /a./ it will match a single “a” followed by any character, and if you have /a+/ it will match one or more "a"s.