Insert a string before the extension in a filename

后端 未结 7 1461
日久生厌
日久生厌 2021-02-05 03:58

How can I insert a string before the extension in an image filename? For example, I need to convert this:

../Course/Assess/Responsive_Course_1_1.png
7条回答
  •  逝去的感伤
    2021-02-05 04:20

    If you are not sure what could be the incoming file's extension then this helps:

    function renameFileA(imgUrl) {
      var extension = `.${imgUrl.split('.').pop()}`
      var [fileName] = imgUrl.split(extension);
      return `${fileName}_large${extension}`;
    };
    
    // this is clean but I don't understand what's going on till I do research ;)
    function renameFileB(imgUrl) {
      return imgUrl.replace(/(\.[\w\d_-]+)$/i, '_large$1');
    };
    
    var valA = renameFileA('http//www.app.com/img/thumbnails/vid-th.png');
    var valB = renameFileB('http//www.app.com/img/thumbnails/vid-th.jpg');
    
    console.log('valA', valA);
    console.log('valB', valB);

提交回复
热议问题