Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  78] [ 2]  / answers: 1 / hits: 127677  / 13 Years ago, tue, july 5, 2011, 12:00:00

The following regex



var patt1=/[0-9a-z]+$/i;


extracts the file extension of strings such as



filename-jpg
filename#gif
filename.png


How to modify this regular expression to only return an extension when string really is a filename with one dot as separator ? (Obviously filename#gif is not a regular filename)



UPDATE Based on tvanofsson's comments I would like to clarify that when the JS function receives the string, the string will already contain a filename without spaces without the dots and other special characters (it will actually be handled a slug). The problem was not in parsing filenames but in incorrectly parsing slugs - the function was returning an extension of jpg when it was given filename-jpg when it should really return null or empty string and it is this behaviour that needed to be corrected.


More From » regex

 Answers
224

Just add a . to the regex


var patt1=/.[0-9a-z]+$/i;

Because the dot is a special character in regex you need to escape it to match it literally: ..


Your pattern will now match any string that ends with a dot followed by at least one character from [0-9a-z].


Example:




[
foobar.a,
foobar.txt,
foobar.foobar1234
].forEach( t =>
console.log(
t.match(/.[0-9a-z]+$/i)[0]
)
)






if you want to limit the extension to a certain amount of characters also, than you need to replace the +


var patt1=/.[0-9a-z]{1,5}$/i;

would allow at least 1 and at most 5 characters after the dot.


[#91349] Sunday, July 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donovantyriqn

Total Points: 271
Total Questions: 98
Total Answers: 113

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;