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];
Marc
  • 13,011
  • 11
  • 78
  • 98

1 Answers1

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]);
Peter B
  • 22,460
  • 5
  • 32
  • 69