Find files with pdf extension Javascript regex

In this post we will use javascript regular expression to get a list of pdf files using Javascript expression.

We will see how to use a regex to find a pdf if you have a list of files as:-

  • string
  • array

If you have list of files as string

Suppose you have a list of files as a huge string separated by space:-

const files = `some-js-file1.js some-js-file2.js some-pdf-file1.pdf some-pdf-file2.pdf some-txt-file1.txt some-png-file1.png`

Here we want to get the pdf files only. We can use the following regular expression:-

const regExForPdf = /\w+\.pdf/g;
files.match( regExForPdf );
// Output
// ['file1.pdf', 'file2.pdf']

If you have list of files as array

Suppose you have a list of files as a array:-

const files = ['some-js-file1.js', 'some-js-file2.js', 'some-pdf-file1.pdf', 'some-pdf-file2.pdf', 'some-txt-file1.txt', 'some-png-file1.png'];

Here we want to get the pdf files only. We can use the following regular expression:-

const regExForPdf = /\w+\.pdf/g;
files.filter( f => regExForPdf.exec(f) );
// Output
//['some-pdf-file1.pdf', 'some-pdf-file2.pdf']

Regular Expression explanation

/\w+\.pdf/g
  • \w – \w will search for individual words.
  • .pdf – will search for words ending with ‘pdf’. You can change this to ‘.txt’ or any other extension that you need to find.

Conclusion

Hope you like the short explanation on how we can use a regular expression to get the list of pdf or any other extension from a list or string. See you in my next post. Till then enjoy coding 🙂