0

How do you use regex to get the file extension? Below is the code I'm trying to do. I tried making a method to get the file extension but seems like the method I was creating isn't working. Anyone can help?

public getExtensionFile(files: FileList): void {
for(let i = 0; i < files.length; i++) {
  const file = files[i]; // files names or list
  let fileDisplay = [];
  const fileType = /[0-9a-z]+$/.exec(file.name);

  fileDisplay['type'] = file.name.split("\\.");
  if(fileType != null ){
    fileDisplay['file'] = file;

  } 
  console.log(fileDisplay[files.length-1]);
 }
}

 this.uploadService.fetchUploadInfo(this.resourceId).subscribe(res => {
  if (res) {
    this.getExtensionFile(res);
    this.histories = res['histories'];

    const model = res['generalInfo'] && res['generalInfo']['model'];
    const selectedTagIds = _.map(res['tag']['resourceTags'], 'tagId');
    const selectedTagItems = _.filter(res['tag']['tags'], function (p) {
      return _.includes(selectedTagIds, p.key);
    });

HTML

<div class="img-box" *ngFor="let file of referenceFiles; let i = index">
          <div (click)="removeFile(i)" class="trash-icon">
            <img src="assets/icons/trash-alt-solid.svg" alt="">
          </div>
          <img [src]="file['absoluteUri'].toLowerCase()">
          <div class="text">
            <span>{{ file.fileStorageId }}</span>
          </div>
Zze
  • 18,229
  • 13
  • 85
  • 118
Ren
  • 57
  • 7

2 Answers2

1

The file extensions include only numbers and alphabets. So you could use something like below.

function getExtensionFile(filename) {
   return (filename.match(/\.[0-9a-zA-Z]+$/i)) ? filename.match(/\.[0-9a-zA-Z]+$/i)[0] : 0;
}

You can use this logic on a for loop to get extension of the file list.

Ayus Mohanty
  • 390
  • 1
  • 8
0

Try with this. You need not split it separately.

function getFileExtension(filename) {
   return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined;
}
sibabrat swain
  • 1,277
  • 8
  • 20