js 擷取檔案字尾名

墨城發表於2022-04-23

方法一:

<input type="file" onChange="change(event)">
<script>
function change(event) {
    var fileName = event.target.files[0].name.toLowerCase();
    var lastIndex = fileName.lastIndexOf('.');
    var suffix = fileName.substring(lastIndex, fileName.length);
    console.log(suffix);
}
</script>

方法二:

<input type="file" onChange="change(event)">
<script>
function change(event) {
    var fileName = event.target.files[0].name.toLowerCase();
    var suffix = fileName.split('.').pop();
    console.log(suffix);
}
</script>

方法三:

<input type="file" onChange="change(event)">
<script>
function change(event) {
    var fileName = event.target.files[0].name.toLowerCase();
    var suffix = fileName.match(/.[^.]+$/)[0];
    console.log(suffix);
}

相關文章