Archive for category JavaScript Regex

JavaScript Regex – Extract Extension from Filename

There are many times during web front-end development that you need to extract extension from filename using Regular Expression. One such time will be when you try to validate the image type when someone try to upload a photo. Below is an example of how to do so:

<html>
<head>
<title></title>
</head>
<body>
<form name="form1">
    <input type="text" name="txtInput" />
    <div id="lblResult"></div>
    <script language="javascript">
        function replace() {
            document.getElementById('lblResult').innerHTML = ➥
document.form1.txtInput.value.replace(➥
/[^\\]+\\[^\\\/:*?\"<>|]+\.([^.\\\/:*?\"<>|]+)/, "$1");
        }
    </script>
    <input type="button" name="btnSubmit" onclick="replace()" value="Go" />
</form>
</body>
</html>

[^\\/:*?"<>|] a character class that doesn’t match invalid filename characters . . .
+ found one or more times.
\. a dot (.), escaped so it has literal meaning . . .
(?<ext> a group named ext that contains . . .
[^.\\/:*?"<>|] a character class that doesn’t match an invalid filename character or another dot (.) . . .
+ found one or more times . . .
) the end of the group.

No Comments