jQuery: repair anchors link on web with BASE tag


/ Published in: jQuery
Save to your folder(s)

on using any wysiwyg editor (f.e. CKEditor) is inserted link to anchor on same page in this form: [a href="#anchor"]text[/a]

if on web site is used tag BASE, anchors links are wrong - on all page are on this url: www.domain.com/#anchor

this function repair this anchor link to correct url


Copy this code and paste it in your HTML
  1. jQuery.repairLink2Anchor = function() {
  2. // exists tag BASE
  3. if ($("base").length) {
  4. // regular expression for anchor link
  5. var re1 = /#([\w-]+)/; // anchor parts
  6. var re2 = /^#([\w-]+)/; // only anchor
  7. // read current url
  8. var thisUrl = document.location.href;
  9. // remove anchor from current url
  10. thisUrl=thisUrl.replace(re1,"");
  11. // inicialization
  12. var href = '';
  13. var anchor = '';
  14. // loop all A tags whith attribute href
  15. $("a[href]").each(function(){
  16. href = $(this).attr("href");
  17. // check - href is anchor?
  18. if (re2.test(href)) {
  19. anchor = href.match(re2);
  20. $(this).attr("href", thisUrl + '#' + anchor[1]);
  21. }
  22. });
  23. }
  24. }
  25.  
  26. /*
  27. start this jQuery function with:
  28. $.repairLink2Anchor();
  29. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.