2

How can I get the value after the very first slash "if a slash is there" from a giving URL?

If the URL is domain.com I want to return empty string.

if the URL is domain.com/index.html I want to also return an empty sting

If the URL is domain.com/dev or domain.com/dev/new/blah.html I want to return 'dev'

Note: I don't know what will be the values after the first slash

Here is what I have done

var icwsSiteBaseURL = document.location.pathname.split("/").slice(1, 2).toString();

My code work for the first and third example but will not return an empty string for the second example. It will return index.html

6
  • Obviously. You didn't specify, but I assume it returns index.html? So, after the line you have, write a simple if statement to check for that and set the variable to '' if it is indeed index.html. Commented Jun 24, 2015 at 19:22
  • I believe what you want cannot be generalized, so you need to be specific. What if the URL is domain.com/my.file where my.file is the name of a file, like your index.html example. What then separates the two cases? Is it only for .html? what about .css, .js, or files like hello.world? And then, how do you know it's not a URL with a separator containing a dot in file name, e.g. `domain.com/index.html/we.like.dots/hello Commented Jun 24, 2015 at 19:25
  • @GolezTrol Sorry I just updated my question, instead of an empty string it return index.html Commented Jun 24, 2015 at 19:26
  • In my question there is note that I don't know what will be the values after the first slash. so index.html can be blah.php or anything else Commented Jun 24, 2015 at 19:30
  • is it specifically index.html that you want to be emtpy? or any page after the first '/' Commented Jun 24, 2015 at 19:32

1 Answer 1

2

You just need to check the result for the values you want to ignore. Here is an example:

var domains = [
  'domain.com',
  'domain.com/index.html',
  'domain.com/dev',
  'domain.com/dev/new/blah.html'
  ];

var results = domains.map(function (domain) {
  // This would be document.location.path in your example
  var path = domain.split('/')[1] || '';

  // Check path if it matches the value you want to ignore
  return { domain: domain, result: path === 'index.html' ? '' : path };
});

document.write('<pre>' + JSON.stringify(results, null, 4) + '</pre>');

So, for your example code:

var icwsSiteBaseURL = document.location.pathname.split("/").slice(1, 2).toString();
if (icwsSiteBaseURL === 'index.html') { icwsSiteBaseURL = ''; }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.