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

VIKAS KOHLI picture VIKAS KOHLI · Feb 21, 2017 · Viewed 7.1k times · Source

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

Answer

Rohit Jindal picture Rohit Jindal · Feb 21, 2017
  • 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]);