Search code examples
javascriptjquerywindow.locationpathname

Window Location Pathname with Multiple Directories


I'm sure this very easy, but I am having trouble writing this path correctly. I have no problems triggering the command using:

if(window.location.pathname.match(/^\/Home-Blog/)) {$('#maincolumn').remove();}

But for another case, I need the pathname to be longer, with the following directory:

/Home-Blog/CategoryBlogID

Any way I try to insert it, it doesn't seem to work. How do I plug in the path to "CategoryBlogID"?

Thank you!


Solution

  • I'm not totally sure I understand your question, but if you want to match

    • /Home-Blog
    • /Home-Blog/
    • /Home-Blog/CategegoryBlogID

    this RegExp should do the trick:

    "/Home-Blog/CategoryBlogIDs".match(/^\/Home-Blog(\/)*(CategoryBlogID)?$/)
    

    /^ start of string

    \/ a forward slash

    Home-Blog the text "Home-Blog"

    (\/)* a forward slash zero or more times (will also match /Home-Blog////CategoryBlogID) because of this

    (CategoryBlogID)? the string "CategoryBlogID" zero or one times

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references