webmonkey237 webmonkey237 - 7 months ago 9
Javascript Question

Extracting the end of a URL and adding it into an href

Why im doing this is to long to explain but im trying to take the last part of a URL and then add it into the start of an anchor tag e.g.

http://www.website.com/page/home


So "home" would end up below:

<div class="officeBtns">
<a class="linkbuttons locBtn" href="home#something1">Button1</a>
<a class="linkbuttons locBtn" href="home#something2">Button2</a>
<a class="linkbuttons locBtn" href="home#something3">Button3</a>
</div>


I dont want to replace the entire href as I still need "#something" on the end.
I also need it to ignore anything on the end of the url for example

http://www.website.com/page/home#blah


or

http://www.website.com/page/home?blah=blah


So far this is my unfinished code:

$(document).ready(function() {
var url = window.location.pathname,
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,''));

$('.officeBtns a').each(function(){
if(urlRegExp.test(this.href.replace(/\/$/,''))){

INSERT URL INTO HREF BEFORE THE #

}
});

});


Thanks

Answer
$(document).ready(function() {
    var url = window.location.pathname;

    var lastSegment = url.substr( url.lastIndexOf( '/' ) + 1);
    var questionMarkIndex = lastSegment.indexOf( '?' );
    if ( questionMarkIndex > -1 ) {
        lastSegment = lastSegment.substr( 0, questionMarkIndex );
    }

    $( '.officeBtns a' ).each( function( index, element ) {
        var href = $( element ).attr( 'href' );
        if( href.indexOf( '#' ) > -1 ) {
            $( element ).attr( 'href', lastSegment + href.substr( href.indexOf( '#' ) ) );
        } else {
            $( element ).attr( 'href', lastSegment );
        }
    });

});