0

I have this code

var url = 'http://sitename.com/category/diving/',
    catName = url.substr(url.lastIndexOf('/') + 1);

And when I try to run alert(catName) it returns empty string. What am I doing wrong?

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112
  • The question is, what do you _want_ it to return? – The Blue Dog Mar 15 '15 at 16:06
  • Try doing some debugging. For example, do `url.lastIndexOf('/')` and you'll see it returns `35` which is the correct index of the last `/`. From there you can go on to solve the other part of your problem. – David Sherret Mar 15 '15 at 16:07

3 Answers3

2

You need the category name but you have to remove first the last /:

var url = 'http://sitename.com/category/diving/';
url = url.substr(0, url.length - 1);
catName = url.substr(url.lastIndexOf('/') + 1);

Result:

"diving"
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1

because you add +1 to the index, so you get undefined string. remove the +1 in the lastIndexOf

David Haim
  • 25,446
  • 3
  • 44
  • 78
0

You can use..parseUri

var url = 'http://sitename.com/category/diving/';
url = url.substr(0, url.length - 1);
var filename1 = parseUri(url ).file;--way1
var filename2 = url.match(/.*\/(.*)$/)[1];

Result="diving";

Ways to achieve this

Community
  • 1
  • 1
A_Sk
  • 4,532
  • 3
  • 27
  • 51