Alon Shmiel
Alon Shmiel

Reputation: 7121

Find first index of a string after index

I have a string: "www.google.com.sdg.jfh.sd"

I want to find the first ".s" string that is found after "sdg".

so I have the index of "sdg", by:

var start_index = str.indexOf("sdg");

now I need to find the first ".s" index that is found after "sdg"

any help appreciated!

Upvotes: 56

Views: 99102

Answers (3)

lukas.pukenis
lukas.pukenis

Reputation: 13597

There's a second parameter which controls the starting position of search:

String.prototype.indexOf(arg, startPosition);

So you can do

str.indexOf('s', start_index);

Upvotes: 153

matewka
matewka

Reputation: 10148

This code might be helpful

var string = "www.google.com.sdg.jfh.sd",
  preString = "sdg",
  searchString = ".s",
  preIndex = string.indexOf(preString),
  searchIndex = preIndex + string.substring(preIndex).indexOf(searchString);

You can test it HERE

Upvotes: 26

jasonslyvia
jasonslyvia

Reputation: 2535

var str = "www.google.com.sdg.jfh.sd";
var search = "sdg";
var start_index = str.substring(str.indexOf(search) + search.length).indexOf(".s");

Upvotes: 2

Related Questions