Insert a string before the extension in a filename

后端 未结 7 1458
日久生厌
日久生厌 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:01
    var s = '../Course/Assess/Responsive_Course_1_1.png'
    s.replace(/\.png$/, '_large.png');
    

    This will do the job. By the way, it's night here. :)

    UPDATE:

    A more general way would be this:

    var s = '../Course/Assess/Responsive_Course_1_1.png';
    s.replace(/(\.[^\.]+)$/, '_large$1');
    
    0 讨论(0)
  • 2021-02-05 04:04

    for files without extension and files includes extension. thanks @paul !

    filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "-thumb" + '$2');

    0 讨论(0)
  • 2021-02-05 04:09

    Either $1 match a filename with no extension or $2 match an extension.

    filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "_large" + '$2');
    
    0 讨论(0)
  • 2021-02-05 04:13

    If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:

    filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
    
    0 讨论(0)
  • 2021-02-05 04:14

    None of the answers works if file doesn't have extension. Here's a solution that works for all cases.

    function appendToFilename(filename, string){
        var dotIndex = filename.lastIndexOf(".");
        if (dotIndex == -1) return filename + string;
        else return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
    } 
    
    0 讨论(0)
  • 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);

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