Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first index of a string after index

Tags:

javascript

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!

like image 252
Alon Shmiel Avatar asked Oct 03 '13 15:10

Alon Shmiel


People also ask

How do I find the first index of a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Does indexOf return the first instance?

JavaScript indexOf() Method: The indexOf() method is a built-in & case-sensitive method that returns the index of the first occurrence of the specified value in the calling string object. It will return -1 if no such value is found.

How do you find the index of the first occurrence of a specific value i from string?

The “find” function has been used to get the index of the first occurrence of an alphabet “I”. This index number will be saved to the variable “index” and the print statement will display it on the shell.

How do you find the index of the first occurrence of character?

To find the position of first occurrence of a string, you can use string. find() method. where string is the string in which you have to find the index of first occurrence of substring . start and end are optional and are starting and ending positions respectively in which substring has to be found.


2 Answers

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); 
like image 150
lukas.pukenis Avatar answered Sep 20 '22 08:09

lukas.pukenis


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

like image 41
matewka Avatar answered Sep 18 '22 08:09

matewka