0

How can we elegantly return a possible string regex match without running the match twice?

// Works fine, returns "pdf"
let ext = "file.with.extension.pdf".match(/\.([a-z]+)$/)[1];
// Exception, we'd like just null or ''
let ext = "nofileextension".match(/\.([a-z]+)$/)[1];
// Duplicate execution
let ext = "nofileextension".match(/\.([a-z]+)$/) && "nofileextension".match(/\.([a-z]+)$/)[1];

Is there no optional chaining ()?[1] for a method which might return an array?

let ext = "nofileextension".match(/\.([a-z]+)$/)?[1];
0

1 Answer 1

2

You can use ?. and then the array indexing will only be done if an object is present to do it on:

console.log("document123.pdf".match(/\.([a-z]+)$/)?.[1]);
console.log("nofileextension".match(/\.([a-z]+)$/)?.[1]);

Not the answer you're looking for? Browse other questions tagged or ask your own question.