Replacing filename with a Regex in JavaScript

ぐ巨炮叔叔 提交于 2021-02-11 13:23:57

问题


I need to replace a button using a Regex in JavaScript and was wondering how to do this. 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. Here are the two different file names:

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

Any help would be greatly appreciated.


回答1:


To insert a -next before the final dot, you could do

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

To remove a -next before the final dot:

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



回答2:


if (url.match(/-next/))
    newUrl = url.replace("-next.", ".");
else newUrl = url.replace(".", "-next.");



回答3:


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.




回答4:


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



回答5:


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

src1 = src1.replace(/\.(\w+)/, "-next.$1");
src2 = src2.replace("-next", "");



回答6:


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.



来源:https://stackoverflow.com/questions/5331419/replacing-filename-with-a-regex-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!