Search code examples
jquerypretty-urls

JQUERY insert string in relative pretty url


I like to insert a string with Jquery only in case of "some" relative pretty url.

the string that must be inserted contains a value of '/1' or '/2' or '/3'

So a url like:

<a href="/whatever"> becomes 
<a href="/1/whatever"> or <a href="/2/whatever"> etc.

But a url like

<a href="/1/whatever"> or 
<a href="/2/whatever"> must keep unchanged

All examples below must keep unchanged.

/whatever/whatever
/whatever/whatever/whatever

<img src="/img.png">
<img src="/whatever/img.png">
<img src="/whatever/whatever/img.png">
<img src="http://whatever.com/img.png">
<img src="http://whatever.com/whatever/img.png">

<a href="http://whatever.com></a>
<a href="http://whatever.com/whatever.whatever></a>
<a href="http://whatever.com/whatever/whatever.whatever></a>

Solution

  • Hi try the following code :

    $(document).ready(function(){
          $ ("a").each(function(){
             var url = $(this).attr("href"),
             count = (url.match(/\//g) || []).length;
             if(count == 1)
             {
                 var cookieValue; //set your cookie value in this variable
                 $(this).attr("href","/"+cookieValue + $(this).attr("href"));
             }
          });
    
          $ ("img").each(function(){
            var url = $(this).attr("src"),
                count = (url.match(/\//g) || []).length;
            if(count == 1)
            {
                var cookieValue; //set your cookie value in this variable
                $(this).attr("src","/" + cookieValue + $(this).attr("src"));
            }
        });
      });