Regexp to add and remove text before completing a file

I want to change src image.

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

on mouseover I want to add _hover to myimage ("/images/myimage_hover.png") and on mouseout I want to remove "_hover".

Does anyone have a good regexp for this?

thank

+3
source share
5 answers

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 other answers, some of them are more complex;) But using attrwith a callback is a good approach.

+5
source

edit oops is "src" for tags <img>, not "href"

Well, you can get the url:

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

Once you get this, you can add "_hover" with:

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

and delete it with

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

, :

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

, "foo_hover_hover.png".

+4

Here is a solution that works regardless of your file extension:

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>
+3
source

Try the following:

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
+1
source

Do you think that you do not save the extension with the file name? If your formats are compatible or if you save the extension separately, you can make your life easier. Thus, if your naming scheme changes, the likelihood of violating your regular expression is lower.

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

Source: https://habr.com/ru/post/1789034/


All Articles