find the extension of a json file in javascript

To find the extension of a JSON file in JavaScript, you can use a regular expression to extract the file extension from the filename. Here is an example function that takes a filename as input and returns the file extension:

index.tsx
function getFileExtension(filename) {
  return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
}
108 chars
4 lines

This function uses the lastIndexOf method of the string object to find the position of the last dot in the filename, which separates the file name from its extension. It then uses the slice method to extract the extension, which is everything after the last dot. The >>> 0 and + 2 expressions are used to handle the case where there is no dot in the filename, in which case the lastIndexOf method returns -1 and the slice method returns the entire filename, which would also include the dot.

You can use this function to extract the file extension from a filename as follows:

index.tsx
const filename = "data.json";
const fileExtension = getFileExtension(filename);
console.log(fileExtension); // outputs "json"
126 chars
4 lines

This code assumes that the filename has a valid extension, i.e., it contains a dot followed by one or more characters. If the filename does not have a valid extension, the function will return the entire filename.

gistlibby LogSnag