CSE 154 Examples

Occurence and position of a substring in a string

Description :

In Javascript we can use the indexOf method to find the FIRST occurence(starting index) of a string in another string.
The lastIndexOf method can be used to find the LAST occurence(starting index) of a string in another string.
You can also specify which index to start searching from as a second parameter.
Note that JS starts counting from 0. If there are no results -1 is returned.

Syntax : let changed_string = original_string.indexOf(query_string);

let changed_string = original_string.indexOf(query_string, index_to_start);

let changed_string = original_string.lastIndexOf(query_string);

Examples :

						
	            let firstWord = "tree";
	            let sentence = "A tree";
	            let position = sentence.indexOf(firstWord);
						
	            position = ??
          
						
	            let firstWord = "apple";
	            let sentence = "apple apple is not apple";
	            let position = sentence.lastIndexOf(firstWord);
	            let secondPosition = sentence.indexOf(firstWord, 5);
						
            position = ??
            secondPosition = ??
          
						
	            let firstWord = "no";
	            let sentence = "yes is a valid response";
	            let firstPosition = sentence.indexOf(firstWord);
	            let lastPosition = sentence.lastIndexOf(firstWord);
						
            position = ??
            lastPosition = ??