Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get characters from second last index using indexof in javaScript?

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"     
var n = absoluteURL.lastIndexOf('/');
var result = absoluteURL.substring(n + 1);
//alert(result);
console.log(result);

Here I get the result like 'vikas-kohli' as I am using lastIndexOf.

Now if someone wants to get characters from second last index, or it may be 3rd last index, then how can I get this?

I hope I am able to explain my question well

like image 356
VIKAS KOHLI Avatar asked Feb 21 '17 10:02

VIKAS KOHLI


Video Answer


1 Answers

  • Insteadof using lastIndexOf('/') use string split('/') method.

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"     
var splittedStr = absoluteURL.split('/');
console.log(splittedStr);
  • Then get the required element from an array.

    var res = splittedStr[splittedStr.length-n]; // n: 1,2,3.. cosnole.log(res);

DEMO

var absoluteURL = "http://stackoverflow.com/users/6262169/vikas-kohli"     
var splittedStr = absoluteURL.split('/');
console.log(splittedStr[splittedStr.length-2]);
like image 56
Creative Learner Avatar answered Sep 20 '22 22:09

Creative Learner