简体   繁体   English

用JavaScript中的正则表达式替换文件名

[英]Replacing filename with a Regex in JavaScript

I need to replace a button using a Regex in JavaScript and was wondering how to do this. 我需要使用JavaScript中的Regex替换按钮,并且想知道如何执行此操作。 I know how to grab the src of the button, but I need to take the filename and either add some text "-next" or remove "-next", based on two options that can be toggled. 我知道如何获取按钮的src,但是我需要获取文件名并根据两个可以切换的选项添加一些文本“ -next”或删除“ -next”。 Here are the two different file names: 这是两个不同的文件名:

/images/button.png
/images/button-next.png

Any help would be greatly appreciated. 任何帮助将不胜感激。

To insert a -next before the final dot, you could do 要在最后一个点之前插入-next ,您可以执行

result = subject.replace(/(?=\.[^.]+$)/g, "-next");

To remove a -next before the final dot: 要在最后一个点之前删除-next

result = subject.replace(/-next(?=\.[^.]+$)/g, "");

That looks to me like what you need is pretty simple: 在我看来,您所需要的非常简单:

if (addingNext) {
    return str.replace(/\.png$/i, '-next.png');
} else {
    return str.replace(/-next\.png$/i, '.png');
}
if (url.match(/-next/))
    newUrl = url.replace("-next.", ".");
else newUrl = url.replace(".", "-next.");
function toggle(img){
    if(img.src.match(/-next\.[^\.]+$/)){
        img.src=img.src.replace(/\.[^\.]+$/,'-next$&');
        return true;
    }
    img.src=img.src.replace(/-next(\.[^\.]+)$/,'$1');
    return true;
}

Works on any file extension. 适用于任何文件扩展名。

var src1 = "/images/button.png";
var src2 = "/images/button-next.png";

src1 = src1.replace(/\.(\w+)/, "-next.$1");
src2 = src2.replace("-next", "");
var str = "/images/button.png";
    var idx = str.lastIndexOf('.');
    var replValue = "-next";
    var newStr = str.substring(0,idx) + replValue +
str.substring(idx);

There are probably more efficient ways, but that would work. 可能有更有效的方法,但这是可行的。 You'd also want to test for no . 您还想测试否。 found. 找到了。 You can also use a regex but that is more explicit. 您也可以使用正则表达式,但这更为明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM