Sonu
Sonu

Reputation: 31

Deleting part of href using JQuery

Hi I have few bookmarks in the CMS:

 <li><a href="#online">Chat Online</a> </li>
 <li><a href="#termsOfService">Terms of Service</a> </li>

But CMS is adding some url before # in the link which breaks my functionality. Is there any way to delete everything before # in a link using Jquery. Thanks for the help

Upvotes: 3

Views: 773

Answers (3)

Charles
Charles

Reputation: 323

You could write a regular expression to remove everything before the hash in the href attribute. I'd suggest doing it on the server-side, but if you must use jQuery it might look something like this:

$('li a').each(function () {
    var href = $(this).attr('href').replace(/.*(#.*)$/, "$1");
    $(this).attr('href', href);
});

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this

Working demo

$(function(){
    $("a").each(function(){
        if(this.href && (this.href.indexOf("#") != -1)){
           this.href = this.href.split("#")[1];
        }
    });
});

Upvotes: 0

Gonzalo
Gonzalo

Reputation: 992

These elements have an id? If they do, you could do something like this, being XXX the internal id of each element

$(document).ready(function() {
    var href = $('#XXX').attr('href');
    href = href.split('#')[1]; 
    $('#XXX').attr('href', href);
});

If you wish to apply this to every anchor in you page, then:

$(document).ready(function() {
    $('a').each(function () {
        var href = $(this).attr('href');
        href = href.split('#')[1]; 
        $(this).attr('href', href);
    });
});

Hope this helps

Upvotes: 0

Related Questions