1

I am trying to make a code in javascript which is about IMDB.

When the page loads i want the code to check the URL in the browser bar

and take into a variable only one thing For example when we join

http://www.imdb.com/title/tt0241527/?ref_=nv_sr_1

it should take ONLY the tt0241527

and put it into a variable called searchTerm.

I have searched some posts but i couldnt help myself.

Is it possible for someone to help me test it in my chrome console ??

Lets say that i use this

var pathname = window.location.pathname;
console.log(pathname);

its showing this

/title/tt0241527/

but i want to delete /title/ and the last /

That's my problem

Thanks a lot !

  • 1
    Hum. Did you try anything ? What's the problem ? Assuming you don't know regular expressions, you could `split` `location.pathname`, no ? – Denys Séguret Jul 06 '15 at 07:57
  • @DenysSéguret the problem is that i dont know a lot about javascript and dont know where to start. –  Jul 06 '15 at 07:59
  • 1
    Start by searching. For example "parse URL javascript" – Denys Séguret Jul 06 '15 at 07:59
  • you could, for instance check these questions. Your answer is in them: http://stackoverflow.com/questions/406192/get-current-url-in-javascript?rq=1 http://stackoverflow.com/questions/6944744/javascript-get-portion-of-url-path?rq=1 – mondjunge Jul 06 '15 at 08:03

4 Answers4

1

Assuming the "ID" it's always after the /title/ path, you should do the following:

var str = location.pathname;
var l = str.split("/");
var id = l[l.indexOf("title")+1];

You could use regex, but if you are new to javascript, better do it this way.

Neoares
  • 439
  • 11
  • 24
1

If you’re certain (i.e. already made sure) that window.location.pathname is something like /title/tt0241527/, you could just remove the undesired characters using replace with a regular expression:

var searchTerm = window.location.pathname.replace(/(\/title\/|\/$)/g,'');
console.log(searchTerm); // e.g. === 'tt0241527'
dakab
  • 5,379
  • 9
  • 43
  • 67
  • Thank you a lot! this is what i was trying to do! –  Jul 06 '15 at 08:16
  • That’s great and you’re welcome. Of course, this is no actual URL parsing. You also could [match](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match) `location.href` with a more sophisticated regex. – dakab Jul 06 '15 at 08:26
0

As long as this is a consistent url pattern:

var url = "http://www.imdb.com/title/tt0241527/?ref_=nv_sr_1";

Get the length of the string

var len = url.length;

Remove the http://

url = url.substr(7, len-7);

Split up string into array based on the forward slash

var urlArray = url.split("/");

var domain = urlArray[0];
var title = urlArray[1];
var searchTerm = urlArray[2];
var queryString = urlArray[3];
Peter Campbell
  • 661
  • 1
  • 7
  • 35
0

You can use replace with regex

window.location.pathname.replace(/\/title\/|\/$/g,"")
Gehad Mohamed
  • 131
  • 1
  • 6