How to extract a file name from a path, replace whitespaces, and make it lowercase using RegEx in TypeScript

2 Answers

0 votes
// Extract only the file name.
// Replace File name with lowercase.
// Replace whitespaces with underscores.

let filename: string = "c:\\path\\to\\file\\WITH Whitespace1 and Whitespace2.ts";

filename = filename.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1");
filename = filename.replace(/\s/g,"_");
filename = filename.toLowerCase();

console.log(filename);

 
 
/*
run:
 
"with_whitespace1_and_whitespace2.ts"
 
*/

 



answered Jul 15 by avibootz
0 votes
function normalizeFilename(filePath: string): string {
  // Extract only the file name
  let filename: string = filePath.replace(/^.*[\\\/]([^\\\/]*)$/i, "$1");

  // Replace whitespaces with underscores
  filename = filename.replace(/\s/g, "_");

  // Convert to lowercase
  filename = filename.toLowerCase();

  return filename;
}

const filePath: string = "c:\\path\\to\\file\\WITH Whitespace1 and Whitespace2.ts";
const result: string = normalizeFilename(filePath);

console.log(result); 

 
 
/*
run:
 
"with_whitespace1_and_whitespace2.ts" 
 
*/

 



answered Jul 15 by avibootz
...