0

I'm currently hardcoding testing if a file extension is in a string.

My hardcode way with one extension is

var extension = /(\.txt)$/i;

var testFile = "myTest.txt";

alert(extension.test(testFile)); 

I plan to make this database driven and sent the file extensions in a comma separated list.

How can I parse a comma separated list and test if my String extension is in that list?

var testFile = "mytest.txt"
var validExtensions = "xlsx,txt,csv";
2
  • Split and compare each? Commented Mar 12, 2015 at 19:38
  • Somebody actually down-voted this. I swear some of the people on this site are on a serious high-horse. Commented Mar 12, 2015 at 20:15

3 Answers 3

3

You should use the OR operator, pipeline.

var extension = /(\.txt|\.xls|\.csv)$/i;

Using input string:

var extensionsString = 'csv|txt|xlsx';
var pattern = new RegExp('(\.)(' + extensionsString + ')$', 'ig');
console.log('somepath/somefile.txt'.match(pattern));
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need regular expressions to assert the position of the match at the end of the string.

Instead, you can use ECMAScript6 String.prototype.endsWith, which can be polyfilled.

validExtensions.split(',').some(ext => testFile.endsWith('.' + ext));

Comments

0

Split an array and use each item in your regular expression:

validExtensions.split(',').some(function(ext) {
  return new RegExp('(\.' + ext + ')$').test(fileName);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.