Back to Freecodecamp

Challenge 92: Extension Extractor

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c7e.md

latest1.3 KB
Original Source

--description--

Given a string representing a filename, return the extension of the file.

  • The extension is the part of the filename that comes after the last period (.).
  • If the filename does not contain a period or ends with a period, return "none".
  • The extension should be returned as-is, preserving case.

--hints--

getExtension("document.txt") should return "txt".

js
assert.equal(getExtension("document.txt"), "txt");

getExtension("README") should return "none".

js
assert.equal(getExtension("README"), "none");

getExtension("image.PNG") should return "PNG".

js
assert.equal(getExtension("image.PNG"), "PNG");

getExtension(".gitignore") should return "gitignore".

js
assert.equal(getExtension(".gitignore"), "gitignore");

getExtension("archive.tar.gz") should return "gz".

js
assert.equal(getExtension("archive.tar.gz"), "gz");

getExtension("final.draft.") should return "none".

js
assert.equal(getExtension("final.draft."), "none");

--seed--

--seed-contents--

js
function getExtension(filename) {

  return filename;
}

--solutions--

js
function getExtension(filename) {
  const lastDot = filename.lastIndexOf('.');
  
  if (lastDot === -1 || lastDot === filename.length - 1) {
    return "none";
  }
  
  return filename.slice(lastDot + 1);
}