Search code examples
javascripturlsegment

Javascript remove url last segment if found is numeric


I have javascript function to map url and hyperlink to highlight menu items, however I can't do this in deeper page with url last segment come with number, which a url looks like: http://localhost/story/89

I want to remove the last url segment if it was a number, so the url will end up http://localhost/story (strip / as well).

/* highlight nav menu */
$(function(){
    $('#topMain li a').each(function(index) {
        if($.trim(this.href) == stripQueryStringAndHashFromPath(window.location.href)) {
            $(this).closest('li').addClass('active')
            .closest('li.parent').addClass('active');
        }
    });
});

function stripQueryStringAndHashFromPath(url) {
    return url.split("?")[0].split("#")[0];
}

Solution

  • You can pass regular expression parameter into split().

    Just add .split(/(\/\d*)$/)[0] to the end of url.split("?")[0].split("#")[0] in your stripQueryStringAndHashFromPath function.

    That new segment of regular expression basically search for a backslash (\/) that is followed by one or more digits (\d*) which is positioned at the end ($) of a string.

    More about regular expression here.

    function stripQueryStringAndHashFromPath(url) {
        url = url.split('?')[0].split('#')[0].split(/(\/\d*)$/)[0];
        return url;
    }
    
    console.log(stripQueryStringAndHashFromPath('http://localhost/story/89'));