0

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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Cofey
  • 11,144
  • 16
  • 52
  • 74
  • Sounds like you may want to use CSS here but without a complete example I can't be sure. Can you post a more realistic example of a) the text you have and b) the text you want in both instances? – Josh M. Mar 16 '11 at 20:43

6 Answers6

2

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, "");
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

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');
}
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
0
if (url.match(/-next/))
    newUrl = url.replace("-next.", ".");
else newUrl = url.replace(".", "-next.");
kim3er
  • 6,306
  • 4
  • 41
  • 69
0
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.

Shad
  • 15,134
  • 2
  • 22
  • 34
0
var src1 = "/images/button.png";
var src2 = "/images/button-next.png";

src1 = src1.replace(/\.(\w+)/, "-next.$1");
src2 = src2.replace("-next", "");
amit_g
  • 30,880
  • 8
  • 61
  • 118
-1
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.

Justin Thomas
  • 5,680
  • 3
  • 38
  • 63