How return name of image from FormControl in ReactivForms

Viewed 81

I want to get the name from FormControl of the image in Angular ReactivForms. I got the full path of the image like file = "C:\fakepath\Screenshot (1).png" but I want only Screenshot (1).png. I using control.value for getting the name of the image. I want to add I do not have this folder in my C: directory C:\fakepath\

This is my method :

 requiredFileType(categoryList: CategoryModel[]) {
    return function (control: FormControl) {
      const file = control.value;
      if (file) {
        const extension = file;

        for (let i = 0; i < categoryList.length; i++) {

          for (let j = 0; j < categoryList[i].productModel.length; j++) {
            for (let k = 0; k < categoryList[i].productModel[j].imageProduct.length; k++) {
              console.log(categoryList[i].productModel[j].imageProduct[k].image_path);
              if (categoryList[i].productModel[j].imageProduct[k].image_path.includes(extension)) {
                console.log(categoryList[i].productModel[j].imageProduct[k].image_path);

                return{
                  requiredFileType: true
                };

              }
            }

          }

        }
        return null;

      }

      return null;

    };
  }

Does anyone know the resolution of this?

2 Answers

Use substring if your path has static number of characters (not changing):

const file = control.value;
const fileName = file.substring(10, str.length);

Demo:

let str = "C:\fakepath\Screenshot (1).png";
const mystr = str.substring(10, str.length);
console.log(mystr)

You can use the substring() and lastIndexOf() functions in javascript

const path = control.value;
const fileName = path.substring(path.lastIndexOf('\') + 1, path.length);
Related