How to trim a file extension from a String in JavaScript?

前端 未结 23 2008
醉酒成梦
醉酒成梦 2020-11-30 17:21

For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let\'s assume the file nam

23条回答
  •  渐次进展
    2020-11-30 17:31

    I don't know if it's a valid option but I use this:

    name = filename.split(".");
    // trimming with pop()
    name.pop();
    // getting the name with join()
    name.join('.'); // we split by '.' and we join by '.' to restore other eventual points.
    

    It's not just one operation I know, but at least it should always work!

    UPDATE: If you want a oneliner, here you are:

    (name.split('.').slice(0, -1)).join('.')

提交回复
热议问题