How to replace delve with conditional chaining in a vs code project?
e.g.
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")
desired result
seo?.meta
item?.image.data.attributes.alternativeText
Is it possible using find/replace in Visual Studio Code?
CodePudding user response:
I propose the following RegEx:
delve\(\s*([^,] ?)\s*,\s*['"]([^.] ?)['"]\s*\)
and the following replacement format string:
$1?.$2
Explanation: Match delve(
, a first argument up until the first comma (lazy match), and then a second string argument (no care is taken to ensure that the brackets match as this is rather quick'n'dirty anyways), then the closing bracket of the call )
. Spacing at reasonable places is accounted for.
which will work for simple cases like delve(someVar, "key"
) but might fail for pathological cases; always review the replacements manually.
Note that this is explicitly made incapable of dealing with delve(var, "a.b.c"
) because as far as I know, VSC format strings don't support "joining" variable numbers of captures by a given string. As a workaround, you could explicitly create versions with two, three, four, five... dots and write the corresponding replacements. The version for two dots for example looks as follows:
delve\(([^,] ?)\s*,\s*['"]([^.] ?)\.([^.] ?)['"]\s*\)
and the format string is $1?.$2?.$3
.
You write:
e.g.
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")
desired result
seo?.meta
item?.image.data.attributes.alternativeText
but I highly doubt that this is intended, because delve(item, "image.data.attributes.alternativeText")
is in fact equivalent to item?.image?.data?.attributes?.alternativeText
rather than the desired result you describe. To make it handle it that way, simply replace [^.]
with .
to make it accept strings containing any characters (including dots).