0

I have link like this: How can I convert that to this. To all this instead jay-z it could be anything.

Here is my example code:

$('body a').each(function() {
      var link = $(this).attr('href');
      if(link.indexOf('/category/music/') >= 0) {
          // ...
      }  
 });

So how it can be changed?

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Vlad Ivanov
  • 111
  • 1
  • 7

3 Answers3

1

You are very close.. To modify all links that contains a substring like /category/music/ you can do:

$('a').each(function () {
  if (this.href.indexOf('/category/music/') !== -1) {
    this.href += '?param=1');
  }
});
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
1

I'm guessing you want to append the querystring to the href value of links on a page. If so, this will do what you need...

$("body a").each(function() {
    var $this = $(this);
    var link = $this.attr("href");
    if(link.indexOf('/category/music/') >= 0) {
        $this.attr("href", link + "?param=1");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="http://example.com/category/music/jay-z">Jay-Z</a><br/>
<a href="http://example.com/category/books/clive-barker">Clive Barker</a><br/>
<a href="http://example.com/category/music/cardiacs">Cardiacs</a>

Run the code snippet and then hover over the links. You'll see the querystring has been appended to the links in the music category.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
  • @YosvelQuintero OP didn't ask for a discussion about performance so I've left it as close to their code as possible, but thanks for modifying your answer so it's no longer a copy/paste of mine, complete with a band that I know you've never heard of ;) – Reinstate Monica Cellio Dec 22 '16 at 13:50
  • @YosvelQuintero Also, don't remove your downvote but bear in mind for future reference that you've just abused the voting system in order to show displeasure at me, rather than mark an answer incorrect. This site is not for making you feel better - points are meant to represent truth. – Reinstate Monica Cellio Dec 22 '16 at 13:54
0

if i get you right, this is your soloution :

var url = "http://example.com/category/music/jay-z/";

var stringToAttach = "?param=1"

urlArray = url.split('/');
var stringToCheck = urlArray[urlArray.length - 2]; //stringToCheck = 'jay-z'
if (stringToCheck != stringToAttach )
    url += stringToAttach; 
Developer
  • 460
  • 4
  • 17