56

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!

1
  • What do you mean by "find the first .s index"? You want to find its position in the string? Commented Oct 3, 2013 at 15:17

3 Answers 3

153

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);
Sign up to request clarification or add additional context in comments.

Comments

26

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

2 Comments

This concept is perfect when using regex for getting the index. indexOf(string), the next answer is obviously better, but in case of new RegExp(searchString, "g").exec(text).index, this is awesome. :-)
Fails when var string = "www.s.g.soogle.com.sdg.jfh.sd";
2
var str = "www.google.com.sdg.jfh.sd";
var search = "sdg";
var start_index = str.substring(str.indexOf(search) + search.length).indexOf(".s");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.