Tuesday, May 4, 2021

Javascript Practice 24: JS Hero - String: indexOf() with from index

 
Question: 

Write a function secondIndexOf, taking two strings and determining the second occurrence of the second string in the first string. If the search string does not occur twice, -1 should be returned.

Example: secondIndexOf('White Rabbit', 'it') should return 10.




Answer: 

function secondIndexOf (s1, s2) {

let x = s1.toLowerCase(); 
let y = s2.toLowerCase();
let z = x.indexOf(y);
let a = x.indexOf(y, z+1);

return a;

}; 

or 

function secondIndexOf (string1, string2) {

let abc = string1.indexOf(string2); 
let def = string1.indexOf(string2, abc+1);

return def; 

};

> function secondIndexOf has to perform two tasks 
> it has to ignore the case (lower or upper) for both the strings
> it has to return the position of the second occurence of a specified value in a string, in this case s2 or string2
> in the first answer, we define a variable x and initialize it with a value which converts the s1 parameter to the lower case
> we then define another variable y and initialize it with a value which converts the s2 parameter to the lower case
> since the indexOf() method is case sensitive it is better to convert the strings to a similar case 
> we then declare a variable z and initialize it with the value x.indexOf(y)
where x = lower case of s1
where y = lower case of s2
x.indexOf(y) will give us the first occurrence of y in x
> finally we declare another variable a and initialize it with the value x.indexOf(y, z+1)
> by giving input of 'z+1' it enables the search of the string after the first occurence has been found
> the second answer does the same thing but there is no conversion of case being done
> we have simply declared a variable abc that initializes itself with a value of the first occurence of string2 in string1
> we then declare another variable def and initialize itself with a value that is returned, when we instruct the function to start the search from the first occurence by adding 1 to the variable abc = abc +1
> we then end the function statement by return def which will give us the value we need





No comments:

Post a Comment