VS Code: What if I Need to Replace Something with $?

Written by bob.js | Published 2020/09/10
Tech Story Tags: visual-studio-code | regex | vscode | web-development | coding | programming | microsoft | software-development | web-monetization

TLDR In a previous article about VS Code, Search-and-Replace using RegEx, I had a question that prompted me to create this article so that I can remember what I did. The solution, as I see it is actually in two parts. First, we need to properly select the content for replacement. Then, second, we must define the replacement, accounting for the dollar-sign. The dollar sign after the equal sign seems to be where the main concern of the question comes from.via the TL;DR App

In a previous article about VS Code, Search-and-Replace using RegEx, I had a question that prompted me to create this article so that I can remember what I did ...

The Question

What if I need to replace something with $? For example, replace
$var
with
$this->var = $var
, the regex to search is easy, the problem is the replacement. I (have tried this) with
$this->$1 = $$1
(and) it does not work properly. So how do we go about it?

The Solution

The solution, as I see it is actually in two parts. First, we need to properly select the content for replacement. Then, second, we need to define the replacement, accounting for the dollar-sign ...

Selecting the Content

When I started breaking down the question in my head, I saw some content like the following ...
$var;
$content;
$question;
... the assumption being that this should be changed into ...
$this->var = $var;
$this->content = $content;
$this->question = $question;
So, this means I need to capture the text after the dollar sign. As stated in the question, this is pretty straight forward. There are many ways to do this. I chose ...
\$([a-zA-Z0-9]*)

Replacing the Content

The dollar-sign after the equal sign seems to be where the main concern of the question comes from. I will admit that it took me a few minutes to get my head around the issue of escaping it.

Original Attempt

First, I tried this replacement RegEx ...
$this->$1 = $$1
... this is shown in the question and makes sense; however, the result is ...
$this->var = $1

Escaping the Dollar-Sign

... then, I tried escaping the dollar-sign after the equal-sign ...
$this->$1 = \$$1
... however, the result is not quite what I expected ...
$this->var = \$var

Proper Escaping of the Dollar-Sign

While this is closer, there is clearly something wrong with this approach. I then started searching for how to properly escape the dollar-sign in a RegEx Search-and-Replace.
I found the following ...

The Solution

And, here's the answer ...
$this->$1 = $$$1
... try it out, it works!
Also published on Dev.to

Written by bob.js | REAL, FUN, GEEK who is passionate about Front-End!
Published by HackerNoon on 2020/09/10