开发者

Regexp to add and remove text before file ending

开发者 https://www.devze.com 2023-02-07 13:34 出处:网络
I want to change the src of an image. var string = \"/images/myimage.png\"; on mouseover I want to add _hover to myimage (\"/image开发者_如何学JAVAs/myimage_hover.png\")

I want to change the src of an image.

var string = "/images/myimage.png";

on mouseover I want to add _hover to myimage ("/image开发者_如何学JAVAs/myimage_hover.png") and on mouseout I want to remove "_hover".

Does anyone have a good Regexp for this?

Thanks


One idea:

$('#imageid').hover(function() {
    $(this).attr('src', function(i, val) {
        return val.replace(/^(.+)(\..+)$/, '$1_hover$2');
    });
},
function() {
    $(this).attr('src', function(i, val) {
        // assuming image names don't contain other `_hover` text
        return val.replace('_hover', ''); 
    });
});

Update: Also check the expressions of the other answers, some are more sophisticated ;) But using attr with a callback is a good approach.


edit oops - it's "src" for <img> tags, not "href"

Well you can get the URL itself with:

 var imgUrl = $('#imageId').attr('src');

Once you've got that, you can add the "_hover" with:

 imgUrl = imgUrl.replace(/^(.*)\.png$/, "$1_hover.png");

and remove it with:

 imgUrl = imgUrl.replace(/_hover\.png/, '.png');

Thus to set things up for proper hovering:

 $('#imageId').hover(
   function() {
     var $img = $(this);
     if (!/_hover\.png$/.test($img.attr('src')))
       $img.attr('src', $img.attr('src').replace(/^(.*)\.png$/, '$1_hover.png');
   },
   function() {
     var $img = $(this);
     $img.attr('src', $img.attr('src').replace(/_hover\.png$/, '.png');
   }
 );

I included a test in the first function to try and prevent "foo_hover_hover.png" from happening.


Here's a solution which works no matter what your file extension is:

yourString = yourString.replace(/^(.+)\.([^.]+)$/, '$1_hover.$2'); // do this onmouseover
yourString = yourString.replace(/^(.+)_hover\.([^.]+)$/, '$1.$2'); // do this onmouseout

Demo:

js> var yourString = 'meow.test.png';
js> yourString = yourString.replace(/\.([^.]+)$/, '_hover.$1');
meow.test_hover.png
js> yourString = yourString.replace(/_hover\.([^.]+)$/, '.$1');
meow.test.png
js>


Try this:

var testString = '"/images/myimage.png';
var regExp = /(.*)(\.)(.*)/g;
var testHover =  testString.replace(regExp, "$1_hover$2$3")
alert(testHover); //Hover Image
alert(testString.replace("_hover", ""));//Regular Image


Have you considered not storing the extension with the filename? If your formats are consistent or if you store the extension separately you can make your life easier. That way, if your naming scheme changes, the chances of your regex breaking are lower.

i.e.
var str = "/images/myimage" + (is_selected ? "_hover" : "") + ".png"
0

精彩评论

暂无评论...
验证码 换一张
取 消