In December 2019,
optional
chaining
went to
TC39
stage 4
. Here is a regular expression to replace most instances of
foo && foo.bar
and
baz && baz()
with optional
chaining.
Find:
(\s)([.a-zA-Z]+) &&[\n\s]*(\2).?([^\s])
Replace:
$1$3?.$4
Before:
const t1 = callback && callback(result);
const t2 = filename && filename.lenght;
const t3 =
error &&
error.innerError &&
error.innerError.code === 'invalid_token';
After:
const t1 = callback?.(result);
const t2 = filename?.lenght;
const t3 =
error?.innerError &&
error.innerError.code === 'invalid_token';
Isn't that nicer? Thank you TC39 and VS Code!
A further challenge is to find a regex that will cause the following replacement:
Before:
const t3 =
error?.innerError &&
error.innerError.code === 'invalid_token';
After:
const t3 = error?.innerError?.code === 'invalid_token';
Maybe someday.