使用 JavaScript 替换文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5334053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:50:54  来源:igfitidea点击:

Replace filename using JavaScript?

javascriptregexreplace

提问by Cofey

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.

有人可以告诉我如何在 JavaScript 中执行以下操作吗?我知道如何获取图像的 src,我只想用新的东西替换文件名。

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

/image/any/path/NEWTEXT.png

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

/图像/任何/路径/NEWTEXT.png

回答by Matthew Flaschen

Case-insensitive version:

不区分大小写的版本:

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

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

删除 / 之后的 i 以使其区分大小写。

回答by ridgerunner

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

所有其他解决方案,到目前为止假设有实际IS的路径。它们仅在至少有一个正斜杠时才起作用。此测试函数适用于所有情况,包括空路径:

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 = '' + newname + '.';
    text = text.replace(re, rep_str);
    return text;
}

回答by Winfred

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

回答by James Sulak

Another option:

另外一个选择:

var filename = "/image/any/path/NEWTEXT.png";
var splitFilename = filename.split("/");
var newPath = s.slice(0, s.length).join("/") + newFilename;

回答by ShinyDarkStone

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

javascript 它对文件确实有限制。我假设您想在服务器上执行此操作。如果是这样,您应该使用服务器端脚本,而不是客户端。也许你在谈论 ajax 脚本,如果你能进一步解释一下,也许我可以帮你