Javascript выделить расширение файла

JavaScript — How to get the extension of a filename tutorial

Sometimes, you need to find a file’s extension so you can properly handle the file in your code.

  • Using a combination of the split() and pop() methods
  • Using a combination of substring() and lastIndexOf() methods.

This tutorial will explain both ways, starting from using split() and pop() methods.

Get filename extension using split() and pop() methods

To get a filename extension, you can use a combination of split() and pop() methods.

The split() method will convert a string into an array of substrings, separated by the character you passed as the method’s parameter.

Here’s an example of the split() method in action:

Next, the pop() method will remove the last element of an array and return that as a value. You can assign the result of calling the pop() method into a variable as follows:

Now that you know how the two methods work, you can chain call the methods to get the extension of a filename as follows:

And that’s how you can get the file extension from a filename.

To avoid repeating the code each time you need to extract the extension, you can create a small function called getExtension() that receives one filename parameter as string and return the only the extension as follows:

The method also works well when receiving a file from HTML element as shown below:

 There’s one more way to extract a file extension, let’s learn how to do that next.

Get filename extension using substring() and lastIndexOf() methods

The substring() method is a built-in method of the String object that grabs a part of a string from the start and end indices that you specified as its arguments.

Keep in mind that the end index is excluded from the result, so you need to select the next index of the character you want to include in the substring.

For example, you can extract «ors» from «Horse» with the following code:

A string index starts at 0 so the letter «o» from «Horse» will have an index of 1 .

The letter «s» from «Horse» has an index value of 3 , so you need to put 4 as the second parameter of the substring() method.

When you omit the second parameter, the method will return the rest of the string without cutting it:

Next, the lastIndexOf() returns the index value of a specified string’s last occurrence. You need to specify what you want to look for as an argument to the method.

For example, here’s how to return the last index of «a» from «Banana» :

The letter «a» from the word «Banana» above has the index value of 1 , 3 , and 5 , so the lastIndexOf() method returns only the last one, which is 5 .

Knowing how the two methods work, you can call the lastIndexOf() method to get the index position of the last dot . symbol in a file name, then call the substring() method to extract the extension.

To make your code more concise, you can call both methods in one line as shown below:

And thats how you can extract a file extension using substring() and lastIndexOf() methods.

Just like with split() and pop() methods, you can write a small helper function to get the extension so you don’t have to repeat yourself each time you need it:

Any time you need to grab the extension, just call on the getExtension() method as shown above 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Node.js получить расширение файла

Im создает функцию загрузки файла в node.js с выражением 3. Я хотел бы захватить расширение файла изображения. поэтому я могу переименовать файл, а затем добавить к нему расширение файла.

app.post('/upload', function(req, res, next) < var is = fs.createReadStream(req.files.upload.path), fileExt = >>>> I want to get the extension of the image here ); 

@Jojje, так что решись. В заголовке и теле вашего вопроса запрашивается способ определения типа файла. Так в чем именно твоя проблема? Покажите нам некоторый код, скажите, что вы ожидаете от него, и что он делает вместо этого.

9 ответов

Я считаю, что вы можете сделать следующее, чтобы получить расширение имени файла.

var path = require('path') path.extname('index.html') // returns '.html' 

Только будьте осторожны, он будет захватывать символы только после последней точки, поэтому имена файлов, такие как app.css.gz будут возвращать только .gz а не .css.gz , что может или не может быть тем, что вы хотите.

Обычно расширение является последним. И когда мы ожидаем более одного, например, tar.gz. лучше проверить, существует ли он в конце концов или нет. используя регулярное выражение, например. «tar.gz $» или созданием функции, которая делает это. как проверить это с конца и вернуться назад и посмотреть, полностью ли это соответствует. и у вас будет эта функция, которая проверяет расширение. ЗАЧЕМ? потому что насчет файлов, таких как jone.lastTest.654654556.tar.gz здесь ожидаемое расширение — tar.gz, но если вы примените любую функцию, которая дает форму 1-й точки, она не будет работать, как вы можете видеть

@AllalMohamed Не совсем проблема в вашем случае. .tar.gz — это просто .tar через gzip. Вы можете выполнить gzip -d foo.tar.gz чтобы получить простой и простой foo.tar . Расширения имеют смысл — вам не нужно знать оба расширения одновременно.

@Qix: для этого я только что привел пример. И да, ваша точка зрения имеет смысл и говорит сама за себя, так интересно, как кто-то не может заметить. Но представление о том, что мы делаем, — это не извлечение файлов, а их проверка. и убедившись, что мы принимаем только tar.gz, а не другой формат, то же самое можно применить и в другой ситуации, во многих случаях расширение может быть больше одного (например, .blade.php). Проверка на это более прямая, и мы всегда можем делать проверки уровень за уровнем. Без разницы. Спасибо за ваш комментарий, это очень полезно.

Я использую эту функцию для получения расширения файла, потому что я не нашел способ сделать это более простым способом (но я думаю, что есть):

function getExtension(filename)

для его использования требуется «путь».

другой метод, который не использует модуль пути:

function getExtension(filename)

Да, это работает. Просто подумал, что будет проще использовать узел. Вот что я сделал: var is = fs.createReadStream(req.files.upload.path), fileType = is.path.split(/[. ]+/).pop();

Вы должны просто использовать модуль path, как указано в ответе @Snowfish’s Snowfish, а не писать свой собственный. Дополнительная информация: nodejs.org/api/path.html#path_path_extname_p

// you can send full url here function getExtension(filename)

Если вы используете экспресс, добавьте следующую строку при настройке промежуточного программного обеспечения (bodyParser)

Это решение поддерживает querystrings!

var Url = require('url'); var Path = require('path'); var url = 'http://i.imgur.com/Mvv4bx8.jpg?querystring=true'; var result = Path.extname(Url.parse(url).pathname); // '.jpg' 

Гораздо эффективнее использовать метод substring() вместо split() и pop()

// returns: 'html' var path = require('path'); path.extname('index.html').substring(1); 

Простое решение без необходимости требовать, которое решает проблему расширения множественного периода:

var filename = 'file.with.long.extension'; var ext = filename.substring(filename.indexOf('.')); //ext = '.with.long.extension' 

Или, если вам не нужна ведущая точка:

var filename = 'file.with.long.extension'; var ext = filename.substring(filename.indexOf('.')+1); //ext = 'with.long.extension' 

Убедитесь, что у файла есть расширение.

Я думаю, что отображение заголовка Content-Type в запросе также будет работать. Это будет работать даже в случаях, когда вы загружаете файл без расширения. (когда имя файла не имеет расширения в запросе)

Предположим, что вы отправляете свои данные с помощью HTTP POST:

POST /upload2 HTTP/1.1 Host: localhost:7098 Connection: keep-alive Content-Length: 1047799 Accept: */* Origin: http://localhost:63342 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryPDULZN8DYK3VppPp Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4 Request Payload ------WebKitFormBoundaryPDULZN8DYK3VppPp Content-Disposition: form-data; name="image"; filename="blob" Content-Type: image/png ------WebKitFormBoundaryPDULZN8DYK3VppPp-- 

Здесь заголовок Content-Type содержит тип mime данных. Сопоставление этого типа mime с расширением даст вам расширение файла:).

Restor BodyParser преобразует этот заголовок в свойство с именем type

File < domain: Domain < domain: null, _events: < . >, _eventsCount: 1, _maxListeners: undefined, members: [ . ] >, _events: <>, _eventsCount: 0, _maxListeners: undefined, size: 1047621, path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8', name: 'blob', **type: 'image/png'**, hash: null, lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST), _writeStream: WriteStream < . >, writable: true, domain: Domain < . >, _events: <>, _eventsCount: 0, _maxListeners: undefined, path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8', fd: null, flags: 'w', mode: 438, start: undefined, pos: undefined, bytesWritten: 1047621, closed: true > > 

Вы можете использовать этот заголовок и выполнять сопоставление расширения (подстрока и т.д.) вручную, но для этого также есть готовые библиотеки. Ниже двух были лучшие результаты, когда я просмотрел Google

и их использование также прост:

 app.post('/upload2', function (req, res)

выше фрагмента будет печатать png для консоли.

Источник

Как извлечь расширение из строки имени файла в Javascript?

как бы получить расширение файла файла в переменной?
например, если у меня есть файл как 1.txt Мне нужна часть txt.

Вариант, который работает со всеми следующими входами:

var re = /(?:\.([^.]+))?$/; var ext = re.exec("file.name.with.dots.txt")[1]; // "txt" var ext = re.exec("file.txt")[1]; // "txt" var ext = re.exec("file")[1]; // undefined var ext = re.exec("")[1]; // undefined var ext = re.exec(null)[1]; // undefined var ext = re.exec(undefined)[1]; // undefined 
(?: # begin non-capturing group \. # a dot ( # begin capturing group (captures the actual extension) [^.]+ # anything except a dot, multiple times ) # end capturing group )? # end non-capturing group, make it optional $ # anchor to the end of the string

Используйте метод lastIndexOf для поиска последнего периода в строке и после этого получите часть строки:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1); 

Я лично предпочитаю разделить строку на . и просто вернуть последний элемент массива:)

var fileExt = filename.split(‘.’).pop();

Если в имени файла нет . , вы получите всю строку.

'some_value' => 'some_value' '.htaccess' => 'htaccess' '../images/something.cool.jpg' => 'jpg' 'http://www.w3schools.com/jsref/jsref_pop.asp' => 'asp' 'http://stackoverflow.com/questions/680929' => 'com/questions/680929' 

Я бы рекомендовал использовать lastIndexOf() в отличие от indexOf()

var myString = "this.is.my.file.txt" alert(myString.substring(myString.lastIndexOf(".")+1)) 

Лучше использовать следующее; Работает всегда!

var ext = fileName.split('.').pop(); 

Это вернет расширение без префикса точки. Можете добавить “.” + ext для проверки на расширения, которые вы хотите поддержать!

var x = "1.txt"; alert (x.substring(x.indexOf(".")+1)); 

note 1: это не будет работать, если имя файла имеет форму file.example.txt
примечание 2: это не удастся, если имя файла имеет вид файл

Это решение, если в вашем файле больше. (точек) в названии.

 

получить значение в переменной, а затем разделить его расширение так же, как это.

var find_file_ext=document.getElementById('filename').value; var file_ext=/[^.]+$/.exec(find_file_ext); 

Я использую следующий код:

var fileSplit = filename.split('.'); var fileExt = ''; if (fileSplit.length > 1) < fileExt = fileSplit[fileSplit.length - 1]; >return fileExt; 

Попробуйте это. Может решить вашу проблему.

var file_name_string = "file.name.string.png" var file_name_array = file_name_string.split("."); var file_extension = file_name_array[file_name_array.length - 1]; 

Источник

Читайте также:  Computer science java courses
Оцените статью