0

I'm trying to get /blog in order to put in url_pathname.

var link = 'http://www.example.com/blog';
alert(url_pathname);

if the link was 'http://www.example.com/blog/post', url_pathname would be /blog/page

I tried the following without success.

var link = 'http://www.example.com/blog';
var url_pathname = link[0].pathname;
alert(url_pathname);

2 Answers 2

2

The pathname properties are only available on the location object and link elements. Assign the string to an anchor, and read the value from the parsed link, as follows:

var link = 'http://www.example.com/blog';
var a = document.createElement('a'); // Create a dummy <a> element
a.href = link;                       // Assign link, let the browser parse it
var url_pathname = a.pathname;
alert(url_pathname);


Explanation of your failed method:

  • link is a string.
  • When you use link[0], you get the first character of the string, h.
  • Then, you're trying to get the pathname property of it. This property is not defined on the string, hence you receive undefined.
    (added this explanation to clarify why JavaScript didn't throw an error)
Sign up to request clarification or add additional context in comments.

Comments

0

Try this, made it less verbose:

//var link = 'http://www.example.com/blog'; // try this
var link = "http://www.example.com/blog/post";
var i = link.indexOf('.com')​​​;//assuming ends in .com, find where it starts
alert(link.substring(i+4));//use +4 to skip .com

See the demo: http://jsfiddle.net/c6MMz/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.