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.
i) makes the regex case insensitive. (? s) for "single line mode" makes the dot match all characters, including line breaks.
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).
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.
test() The test() method executes a search for a match between a regular expression and a specified string.
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]
.
[ "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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With