Regular expression to remove a file's extension

后端 未结 9 1958
死守一世寂寞
死守一世寂寞 2020-11-30 01:09

I am in need of a regular expression that can remove the extension of a filename, returning only the name of the file.

Here are some examples of inputs and outputs:<

相关标签:
9条回答
  • 2020-11-30 01:50

    The regular expression to match the pattern is:

    /\.[^.]*$/
    

    It finds a period character (\.), followed by 0 or more characters that are not periods ([^.]*), followed by the end of the string ($).

    console.log( 
      "aaa.bbb.ccc".replace(/\.[^.]*$/,'')
    )

    0 讨论(0)
  • 2020-11-30 01:52

    Just for completeness: How could this be achieved without Regular Expressions?

    var input = 'myfile.png';
    var output = input.substr(0, input.lastIndexOf('.')) || input;
    

    The || input takes care of the case, where lastIndexOf() provides a -1. You see, it's still a one-liner.

    0 讨论(0)
  • 2020-11-30 01:57

    This will do it as well :)

    'myfile.png.jpg'.split('.').reverse().slice(1).reverse().join('.');
    

    I'd stick to the regexp though... =P

    0 讨论(0)
提交回复
热议问题