Refactoring in Visual Studio Code

Using Find and Replace in Visual Studio Code with Regular Expression to replace strings that match certain patterns. For example, in this particular set of code, we want to replace the lines 

class="img-flag" alt="Polish" height="24">

with

class: "img-flag",  alt: "Polish", height: "24">

We cannot do a direct find and replace on this because the country changes for each tag. We will want to wild card the country for only between the alt="*" for each tag.

Original Code:

<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/Poland.png" class="img-flag" alt="Polish" height="24">Polish</a>
<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/United-Kingdom.png" class="img-flag" alt="English" height="24">English</a>
<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/Spain.png" class="img-flag" alt="Español" height="24">Español</a>

In Visual Studio Code, we can use the regular expression in the search to find that parameter and use it in our replace text. This way we can filter only for those lines the country in the alt tag by searching for alt="(.+?)" and then use alt: "$1" as the replace parameter

Source Search:

class="img-flag" alt="(.+?)" height="24">

Replace: 

), class: "img-flag", alt: "$1", height: "24") %>

Which will result in this:

<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/Poland.png" ), class: "img-flag", alt: "Polish", height: "24" %>Polish</a>
<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/United-Kingdom.png" ), class: "img-flag", alt: "English", height: "24" %>English</a>
<a class="dropdown-item" href="#">
  <%= img_tag(static_path(@conn, "/images/clever/flags/Spain.png" ), class: "img-flag", alt: "Español", height: "24" %>Español</a>

 

 


Home Office

Cherry Hill, NJ

North New Jersey Office

Hasbrouck Heights, NJ

Philadelphia Office

Media, PA

office Hours

Mon - Fri : 8am to 6pm

Social Media