首页 > 解决方案 > Is there a way to find all occurrences of using var with a require, and replacing just those results with const?

问题描述

In VS Code, is there a way to use a regular expression to find all statements which use var to declare a variable that assigns a value using require, and then replace just the var with const?

I have tried searching and I’m unable to find an answer.

This is the attempt at the regex (this part works): var[ 0-9a-zA-Z]*= require

It is the search and replace portion of just a part of the match where I am unsure how to do it, or if it is possible.

I’ve set up a StackBlitz.

In this screenshot, I’m trying to replace

var zlib = require('zlib');

by

const zlib = require('zlib');

Screenshot showing my attempt at regex with search and replace.

标签: regexvisual-studio-code

解决方案


in find section: var(.*?)=(.*?)require\(
in replace section: const$1=$2require(

Find and replace in action

Using round brackets around regex (.*) allows it to become a group which can be referred in the replace section of vscode by using group number $1,$2 and so on

Please read vscode documentation here for detailed explanation

Please read this answer for another example.


推荐阅读