Replace filename using JavaScript?

14,223

Solution 1

Case-insensitive version:

path = path.replace(/(.*)\/.*(\.png$)/i, '$1/NEWTEXT$2')

Remove the i after / to make it case-sensitive.

Solution 2

Another option:

var filename = "/image/any/path/NEWTEXT.png";
var splitFilename = filename.split("/");
var newPath = splitFilename.slice(0, splitFilename.length - 1).join("/")
if (newPath.length !== 0) {
    newPath += "/"
}
newPath += newFilename;

Solution 3

All the other solutions so far assume there actually IS a path. They work only if there is at least one forward slash. This tested functions works in all cases including an empty path:

function rename_img_file(text, newname)
{ // Rename file in a IMG src (no query or fragment)
    var re = /^(.*\/)?[^\/]+\.(png|gif|jpe?g)$/i;
    var rep_str = '$1' + newname + '.$2';
    text = text.replace(re, rep_str);
    return text;
}
Share:
14,223
Cofey
Author by

Cofey

Updated on July 25, 2022

Comments

  • Cofey
    Cofey almost 2 years

    Can someone show me how to do the following in JavaScript? I know how to grab the src of the image, I just want to be able to replace the filename with something new.

    /image/any/path/ANY-TEXT_HERE.png

    /image/any/path/NEWTEXT.png