I have JavaScript code that reads the content of an excel file. The first step is to assign a regex to a variable of the name regex
var regex = /^([a-zA-Z0-9s_!()\.-:])+(.xls|.xlsx)$/;
Then some programming occurs like:
if (regex.test($scope.SelectedFile.name.toLowerCase())) {
At times users submit excel files that in their names, they put commas, and that breaks the regex.
I would like to ask for help so that I can learn how to make this small modification to the current regex (that besides the issues with the commas, it has been working fine) without breaking it due to inexperience.
Any help is good.
Thank you, Erasmo
Advertisement
Answer
Presuming the first character of the file name shouldn’t be as flexible as the rest of the name, and fixing some other problems, the solution should look more like this:
var regex = /^[a-z0-9][-a-z0-9x20_!().:,]*.xlsx?$/i;
You don’t have to do a-z and A-Z, or use that toLowerCase()
in your code, if you simply put the i
flag (for case-insensitive) at the end of the regex.
The space character (x20
) is now the only allowed whitespace. You can just type a space instead, but using plain spaces in regexes isn’t always clear to a human reader of the code.
You don’t need to test xls
and xlxs
seperately, because xlsx?
makes the addition of one (and only one) x
after xls
optional.
If you want the file name to start with something other than a letter or a number, modify first character class.
I also removed unnecessary parentheses.