curly_brackets
curly_brackets

Reputation: 5598

Manipulating a copied attr

I'm working on a simple lightbox script for my website, that wraps a link (A) around a image. The link URL should then be the SRC of the image, but slightly manipulated.

The image URL could look like this: "pb028855_copy_147x110.jpg" and I want it to delete "147x110", from after "copy" to before ".jpg" that is.

My current script, to copy the SRC from the image to the link is like this:

$(function(){
    $('img.withCaption').each(function(){
        var $imgSrc = $(this).attr("src");
        $(this).wrap('<a rel="lightBox" />');
        $(this).parent().attr("href", ""+$imgSrc);
    });
});

How can I use parts of a attr?

Thank you in advance...

Upvotes: 0

Views: 54

Answers (3)

user113716
user113716

Reputation: 322582

If you're not certain exactly what the numbers will be, you could use the replace()(docs) method with a regular expression.

$(function(){
    $('img.withCaption').each(function(){
        var $imgSrc = this.src.replace(/_\d+x\d+\./,'.');
        $(this).wrap('<a rel="lightBox" />')
               .parent().attr("href", ""+$imgSrc);
    });
});

So this:

pb028855_copy_147x110.jpg

will end up as this:

pb028855_copy.jpg

Upvotes: 1

yscik
yscik

Reputation: 879

The attr method simply returns a string, you can manipulate it just like any other one. So a regex replace would work.

$(function(){
    $('img.withCaption').each(function(){
        var imgSrc = $(this).attr("src")*.replace(/_copy_\d+x\d+\.jpg$/, "_copy.jpg")*;
        $(this).wrap($('<a rel="lightBox" />').attr("href", imgSrc);
    });
});

(I cleaned up the wrapping part a bit.)

Upvotes: 0

Capsule
Capsule

Reputation: 6159

They are several ways of manipulating strings, depends of what you exactly want, for example:

$imgSrc = $imgSrc.replace(/thumb/, 'big');

Upvotes: 0

Related Questions