Jordan
Jordan

Reputation: 31

Using Jquery and regular expressions to change part of HREF

I am currently trying to use Jquery to change the href attribute of a link within a DIV so that the URL is changed from file.html to file.jpg...

<div class="gallery">
<a href="file.html">My File</a>

and I want to change it to

<div class="gallery">
<a href="file.jpg">My File</a>

I have seen the post about changing the href attribute using Jquery and understand some of it, but I am at a complete loss about how to change all links ending .html within the div to .jpg. The filename doesn't need to change. Would anyone be able to point me in the right direction for help?

Upvotes: 2

Views: 7144

Answers (4)

Gumbo
Gumbo

Reputation: 655189

Try one of these:

$("div.gallery a").each(function() {
    this.setAttribute("href", this.getAttribute("href").replace(/\.html$/, ".jpg"));
});

$("div.gallery a[href$=.html]").each(function() {
    var href = this.getAttribute("href");
    this.setAttribute("href", href.substr(0, href.length-6) + ".jpg"));
});

The first will select every a inside your div and try to replace .html at the end with .jpg using a regular expression. The the second will only select those that’s href value does end with .html and will replace it with .jpg using simple string operations.

Upvotes: 4

Ryan
Ryan

Reputation: 778

I haven't tested it, but I think this should do it:

$('a', '.gallery').each(function(){
   $(this).attr('href', $(this).attr('href').replace(/\.html$/, '.jpg'));
});

Upvotes: 0

mck89
mck89

Reputation: 19231

var href=$(".gallery a").attr("href");
href=href.replace(/\.html$/,".jpg");
$(".gallery a").attr("href",href);

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532435

Just extract the existing hrefs for elements whose href matches your pattern, then use string replacement to get the new href and set it.

$('a[href$=.html]').each( function() {
    var $this = $(this);
    var href = $this.attr('href').replace(/\.html/,'.jpg');
    $this.attr('href', href );
});

Upvotes: 1

Related Questions