получить имя файла из массива JavaScript по его расширению - PullRequest
0 голосов
/ 04 августа 2020

Как я могу получить имя недопустимого файла из массива filesList после того, как я отфильтровал его по его расширению.

<script>
    // 1- this is the files user has selected
    let filesList = ["000.webm", "001.ini", "01.jpg", "02.jpg", "03.jpg", "04.jpg"];
    // 2- get extensions from selected files
    let selectedFilesExt =  ["webm", "ini", "jpg", "jpg", "jpg", "jpg"];
    // 3- this is the allowed extensions
    let allowedExt =["jpg", "png", "gif", "jpeg", "dwg", "psd", "pdf", "docx", "txt", "zip", "rar", 
"exe", "max"];
    // 4- check if selected files extensions is in allowed extensions and display the not allowed extensions
    let notAllowedExt = ["webm", "ini"];
    // i need to get full name for the not allowed extensions files from filesList array
    // in this case i need to get array like this ["000.webm", "001.ini"]
</script>

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Вам нужно всего два массива. fileList и allowedExt. L oop через массив fileList и разделить имя файла. Проверьте с помощью indexOf , существует ли расширение в вашем массиве allowedExt. Если он не подходит, функция фильтрации записывает его в массив notAllowed.

const filesList = ["000.webm", "001.ini", "01.jpg", "02.jpg", "03.jpg", "04.jpg"];
const allowedExt =["jpg", "png", "gif", "jpeg", "dwg", "psd", "pdf", "docx", "txt", "zip", "rar", 
"exe", "max"];

const notAllowed = filesList.filter(oFile => {
    if(allowedExt.indexOf(oFile.split(".")[1]) === -1){ //if the extension of file in allowed array return true
    return true;
  }
})  

console.log(notAllowed);
0 голосов
/ 04 августа 2020
const filesList = ["000.webm", "001.ini", "01.jpg", "02.jpg", "03.jpg", "04.jpg"];
const allowedExt =["jpg", "png", "gif", "jpeg", "dwg", "psd", "pdf", "docx", "txt", "zip", "rar", 
"exe", "max"];


const notAllowedExt = filesList.filter(file => !allowedExt.includes(/(?:\.([^.]+))?$/.exec(file)[1]))

Мы фильтруем список выбранных пользователем файлов и передаем в качестве условия другую функцию, которая проверяет, находится ли выбранный пользователем файл в разрешенном списке или нет, и мы возвращаем противоположное, потому что мы хотим перечислить только расширения, которые не допускается.

Регулярное выражение должно работать для следующих имен файлов и возвращать расширение:

"file.name.with.dots.txt".  // 'txt'
"file.txt"                  // 'txt'
"file"                      // undefined
""                          // undefined
null                        // undefined
undefined                   // undefined
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...