1

I have the following line:

<a href="page.php">Mt 5: 2</a>

And I use jquery code to echo (match) whatever between the > < brackets and makes the link as follows:

<a href="page.php?q=Mt 5: 2">Mt 5: 2</a>

Now I need the link to be as follows:

<a href="page.php?book=Mt&chapter=5&vmin=2">Mt 5: 2</a>

The code I am currently using to match all is:

$(document).ready(function() {
$("a[href='page.php']").each(function(index, element){
   href = $(element).attr('href');
   $(element).attr('href', href + "?q=" + $(element).text());
});
});

So I need to divide whatever between the > < to three sections respectively:

  1. adds Mt to ?book= → ?book=Mt
  2. adds 5 to &chapter= → &chapter=5
  3. adds 2 to &vmin= → &vmin=2
Mike
  • 2,051
  • 4
  • 28
  • 46

1 Answers1

1

You need to split text of each link and use all three values separately to make your desired href like below:-

$(document).ready(function() {
  $("a[href='page.php']").each(function(index, element){
    href = $(element).attr('href'); // get the href
    text = $(element).text().split(' '); // get the text and split it with space
    $(element).attr('href', href + "?book=" +$.trim(text[0])+"&chapter="+$.trim(text[1].slice(0,-1))+"&vmin="+$.trim(text[2])); //create desired href and replace it with older-one
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="page.php">Mt 5: 2</a><br>
<a href="page.php">Mt 7: 2</a><br>
<a href="page.php">Mt 10: 2</a><br>

Note:-

trim() used to remove extra spaces if the value have any(leading/trailing spaces).

slice() used to remove : from the second value.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98