Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Created September 20, 2020 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleMit/be4790e984410326ea6d9351fd13f1ee to your computer and use it in GitHub Desktop.
Save KyleMit/be4790e984410326ea6d9351fd13f1ee to your computer and use it in GitHub Desktop.
How do I change file extension with javascript?
// https://stackoverflow.com/a/47949440/1366033
function changeExt(fileName, newExt) {
var pos = fileName.includes(".") ? fileName.lastIndexOf(".") : fileName.length
var fileRoot = fileName.substr(0, pos)
var output = `${fileRoot}.${newExt}`
return output
}
console.log(changeExt("img.jpeg", "jpg")) // img.jpg
console.log(changeExt("img.name.jpeg", "jpg")) // img.name.jpg
console.log(changeExt("host", "csv")) // host.csv
console.log(changeExt(".graphqlrc", "graphqlconfig")) // .graphqlconfig
@KyleMit
Copy link
Author

KyleMit commented May 4, 2021

Hey Lakhan, sounds like you'd have to tap into the OS in order to handle copy /paste folder operations. This solution is really just targeted at change the string of a file. You could leverage that in a node job, but there's a lot of other work involved - you might want to ask about it on stack overflow if you can give a clear example of what you're looking to accomplish and what you've tried.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment