Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex for matching/extracting file extension

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.

like image 769
mare Avatar asked Jul 05 '11 11:07

mare


People also ask

What does regex (? S match?

i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.

How do I use regex to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you check if a string matches a regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What is the function to test the matching of a text in a RegExp object in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string.


1 Answers

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.

like image 76
stema Avatar answered Sep 19 '22 15:09

stema