0

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];
}
Ben Koo
  • 79
  • 1
  • 7

3 Answers3

1

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'));
yqlim
  • 6,898
  • 3
  • 19
  • 43
0
    function validateURL(url){ let lastSegment = url.split("/");
        if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))
            console.log("True Last Segmant");
        }
    validateURL("http://localhost/demo/8")

function stripQueryStringAndHashFromPath(url) {
    url = url.split('?')[0].split('#')[0].split(/(\/\d*)$/)[0];
    return url;
}

console.log(stripQueryStringAndHashFromPath('http://localhost/story/89'));
0

function validateURL(url){ let lastSegment = url.split("/");if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))console.log("True Last Segmant"); } validateURL("http://localhost/demo/8");

  • For validating the last segment you can use the below code: – atul gupta Sep 21 '17 at 04:34