Skip to content Skip to sidebar Skip to footer

JavaScript IndexOf() - How To Get Specific Index

Let's say I have a URL: http://something.com/somethingheretoo and I want to get what's after the 3rd instance of /? something like the equivalent of indexOf() which lets me input

Solution 1:

If you know it starts with http:// or https://, just skip past that part with this one-liner:

var content = aURL.substring(aURL.indexOf('/', 8));

This gives you more flexibility if there are multiple slashes in that segment you want.


Solution 2:

let s = 'http://something.com/somethingheretoo';
parts = s.split('/');
parts.splice(0, 2);
return parts.join('/');

Solution 3:

Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches.

String.prototype.nthIndexOf = function(s, n) {
  var i = -1;
  while(n-- > 0 && -1 != (i = this.indexOf(s, i+1)));
  return i;
}

var str = "some string to test";

alert(str.nthIndexOf("t", 3)); // 15
alert(str.nthIndexOf("t", 7)); // -1
alert(str.nthIndexOf("z", 4)); // -1

var sub = str.substr(str.nthIndexOf("t",3)); // "test"

Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in.


Solution 4:

If you want to stick to indexOf:

var string = "http://something/sth1/sth2/sth3/"
var lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
string = string.substr(lastIndex);

If you want to get the path of that given URL, you can also use a RE:

string = string.match(/\/\/[^\/]+\/(.+)?/)[1];

This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /.


Solution 5:

Another approach is to use the Javascript "split" function:

var strWord = "me/you/something";
var splittedWord = strWord.split("/");

splittedWord[0] would return "me"

splittedWord[1] would return "you"

splittedWord[2] would return "something"


Post a Comment for "JavaScript IndexOf() - How To Get Specific Index"