Regular Expressions: Remove Whitespace from Start and End- need explaination

let hello = " Hello, World! ";

let wsRegex = /^(\s+)(.+[^\s])(\s+)$/; // Change this line

let result = hello.replace(wsRegex, ‘$2’); // Change this line

can somoene tell me what’s the meaning of the $2 thing and how it works please ??

$2 is the second captured group

In regex, wrapping patterns in brackets captures them as groups for reuse, kinda like assigning to a variable.
The first captured bracket (\s+) is assigned to \1 within the same pattern and $1 outside the pattern, second captured group (.+[^\s]) is assigned to \2 and $2 and so on…

For example, /^(\s+)(.+[^\s])(\s+)$/; can also be written as /^(\s+)(.+[^\s])\1$/; reusing the first capture group.
If you want to use brackets within patterns without capturing, you can add ?: to ignore the group, just like this (?:\s+) means match it but don’t assign any variable.

hello.replace(wsRegex, ‘$2’) means replace all the match with the second capture group.
Since the first and second capture groups are whitespaces the result will be equal to replace . so . with .so.

1 Like

ThankYou that was very helpful

1 Like