views:

301

answers:

3

I need a regular expression that will properly work, the current one I have is breaking.

The goal is

Normal src for an image is: Image.png

Using jQuery on hover I dynamically find the src of an image and replace it with ImageName-Dn.png

On hover off it sets it back to ImageName.png

My current solution:

$(document).ready(function(){
   $(".myButton").hover(
        function () {
            var s = $(this).attr('src');
            s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0]; 
            $(this).attr('src', s);
        },
        function () {
            var o = $(this).attr('src');
            o = o.replace(/-Dn\./, '.'); 
            $(this).attr('src', o);
        }

    );
});

However for some reason the image at some point gets set to ImageName-Dn.png and then screws up and gets set to ImageName-Dn-Dn.png and so on and so forth. Any Help?

Thanks.

A: 

are you doing this for a mouseover effect? Why not use image sprites? Effectively, you just need to create 1 image that contains both version of the image side by side and set it to the background of an element which will display it.

for example, a 10x10 image and it's mouseover version will become a 10x20 image with the original on top of the mouseover version.

you can then create a 10x10 div with the background-image set to the 10x20 image. Since only the top 10x10 will be displayed, you only see the original version.

Then in javascript you can simply attach to an event a call to

 $(el).style.backgroundPosition = '0px -10px';

on the hover event and

$(el).style.backgroundPosition = '0px 0px';

to reset it

This will shift the background up on the mouse over. Not only is this cleaner than having to deal with regex for a simple image swap, it also reduces the number of files the page has to load.

Hope this helps!

David Chen
A: 
   function () {
        var s = $(this).attr('src');
        if( !s.match(/-Dn\.[a-z]+$/) ) {
          s = s.substring( 0, s.search(/(\.[a-z]+)$/) ) + '-Dn' + s.match(/(\.[a-z]+)$/)[0]; 
          $(this).attr('src', s);
        }
    },
    function () {
        var o = $(this).attr('src');
        o = o.replace(/-Dn\./, '.'); 
        $(this).attr('src', o);
    }

(added conditional)

Devin Ceartas
+1  A: 

A quick fix is to test if the string doesn't already have -Dn in it:

if (!string.match(/-Dn\./))

Also, with the regexes, you don't need to manually split the string and do multiple searches. You can use grouping to receive what you need in a single replace instruction such as:

string.replace(/(.*)\.(.*)/, "$1-Dn.$2")

If you want to read up on regular expressions for Javascript: http://en.wikibooks.org/wiki/JavaScript/Regular_Expressions

Raymond Martineau