开发者

Replace filename using JavaScript?

Can someone show me how to do the following in JavaScript? I know how to grab the src of the imag开发者_开发知识库e, 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


Case-insensitive version:

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

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


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;


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;
}


var url = "/image/any/path/ANY-TEXT_HERE.png";
var mystring = "NEWTEXT";
var ind1 = url .lastIndexOf('/');
var ind2 = url .lastIndexOf('.');

var new_url = url.substring(0,ind1+1 )+ mystring + url.substring(ind2 );
alert(new_url ); 


javascript its really restrictive to files. I assume that you want to do that on a server. if that so, you should use a serverside script, not a client side. Maybe you ar talking about an ajax script if you can explain a ltl further maybe i can lendyou a hand

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜