Mehul Kuriya
Mehul Kuriya

Reputation: 608

Jquery change extension on link on fly

I have set of link in so many pages. Eg:

<ul>
 <li> <a href="someurl/somefile.html"> Some file </a> </li>
 <li> <a href="someurl/somefile1.html"> Some file1 </a></li>
 <li> <a href="someurl/somefile2.html"> Some file2 </a></li>
</ul>

<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>

Now, I want to change html to php extension. without modifying the php code.

I have tried following code but it does not work.

$('a').each(function() {
        $(this).html( $(this).html().replace( ".php", '.html' ) );
 });

Any help will be appreciated .

Upvotes: 4

Views: 255

Answers (4)

Jay Rathod
Jay Rathod

Reputation: 11245

Try with this code.

var href = $(this).attr('href');
href = href.replace( ".php", '.html' ) ;
$(this).attr("href", href);

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You have two issues in your code:

1) You need to modify attribute href and not html of elements

2) You have swapped the arguments for replacing html with php. first argument should be for match and second one for its replacement.

$('a').attr('href',function(i,oldhref) {
    return oldhref.replace( ".html",'.php');
});

Working Snippet:

$(function(){
$('a').attr('href',function(i,oldhref) {
    return oldhref.replace( ".html",'.php');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul> 
 <li> <a href="someurl/somefile.html" target="_blank"> Some file </a> </li>
 <li> <a href="someurl/somefile1.html" target="_blank"> Some file1 </a></li>
 <li> <a href="someurl/somefile2.html" target="_blank"> Some file2 </a></li>
</ul>

<a href="someurl/someotherfile.html" target="_blank"> Some Other file </a>
<a href="someurl/someotherfile1.html" target="_blank"> Some Other file1 </a>

Upvotes: 4

Dhruv
Dhruv

Reputation: 1799

You should use,

$('a').each(function() {
    var href = $(this).attr('href');
    href = href.replace(".php", '.html') ;
    $(this).attr("href", href);
});

Hope this answer will help you.

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Just use replace as below:

$(document).ready(function() {
  $('a').each(function() {
    $(this).attr('href',$(this).attr('href').replace('html','php') );
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li> <a href="someurl/somefile.html"> Some file </a> 
  </li>
  <li> <a href="someurl/somefile1.html"> Some file1 </a>
  </li>
  <li> <a href="someurl/somefile2.html"> Some file2 </a>
  </li>
</ul>

<a href="someurl/someotherfile.html"> Some Other file </a>
<a href="someurl/someotherfile1.html"> Some Other file1 </a>

Upvotes: 1

Related Questions