Grab Tier 1 Page Name

var fsPagePath = window.location.pathname;
  var fsPageURL = fsPagePath.substring(fsPagePath.indexOf('/') + 1);
  console.log(fsPageURL);

How can I grab the tier 1 page name? E.g. if I was on sitepoint.com/community/, it’d just grab “community”. If I was on sitepoint.com/community/test, it’d grab “community”, and on sitepoint.com/community/test/ (note trailing slash), it’d still just grab “community”.

It doesn’t seem like there is a single SO thread that covers this situation.

var fsPageURL = fsPagePath.substring(fsPagePath.indexOf('/') + 1).split("/")[0];

Think I got it (as usual, I need to post before I get it).

Let me know if there is a better way or I’m missing some edge cases. Thank you :slight_smile: .

Maybe it would be a slightly cleaner/more efficient using a regular expression, like

var fsPageURL = fsPagePath.match(/[^\/]+/)[0];

which will simply match the first substring not containing a slash. So you have only one string operation instead of three. :-)

That’s fantastic looking, thank you. I’ll try that out first thing in the morning!

Both are solid solutions, but if you end up needing to do a bit more with URL’s I definitely recommend taking a look at URI.js

Hmm, I can’t seem to detect the homepage with that code?I get a Javascript error saying I can’t read [0] from nulll. Do you think there’s a regex workaround?

Ah yes, this means that the regex didn’t match anything, which happens when you’re at the root of your domain (i.e. fsPagePath === '/'). Din’t think of that! So try this instead:

var fsPageURL = (fsPagePath.match(/[^\/]+/) || [])[0];

In case there is no match, it will return undefined then.

1 Like

Seems to be working great. Thanks!

1 Like

Hmm, why is this not working? I’m trying to see if the regex has “-french” in it.

var fsPageURL = (fsPagePath.match(/[^\/]+/) || [])[0];
  if(fsPageURL.test("-french")) {
    console.log('french');
    language="french";
  }

But I am getting an error in my console saying “test isn’t a function”… What differs from my regex from that SO thread?

You have your’s backwards.

/-french/.test(fsPageUrl); // check if -french is found in the URL
1 Like

That’s fantastic. Thanks Matt. Javascript is still a work in progress…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.