find the extension of a csv file in typescript

To find the extension of a CSV file in TypeScript, you can use string manipulation or regular expressions. Here are two different approaches:

Using string manipulation:

index.ts
const filename = "data.csv";
const extension = filename.split('.').pop();
if (extension === 'csv') {
  console.log("This is a CSV file.");
} else {
  console.log("This is not a CSV file.");
}
192 chars
8 lines

First, we split the filename by the dot character, which separates the name and extension. Then we use the pop() method to get the last element of the resulting array, which is the file extension. Finally, we check if the extension is 'csv' to determine if it is a CSV file.

Using regular expressions:

index.ts
const filename = "data.csv";
const extension = filename.match(/\.([^.]+)$/)[1];
if (extension === 'csv') {
  console.log("This is a CSV file.");
} else {
  console.log("This is not a CSV file.");
}
198 chars
8 lines

Here, we use a regular expression to match the last period character in the filename and everything after it. The match() method returns an array with two elements: the matched string and the matched group, which contains the extension. We access the extension using index 1 of the array. Finally, we use the same conditional statement to check if the extension is 'csv'.

gistlibby LogSnag