Question:
Write a function indexOfIgnoreCase taking two strings and determining the first occurrence of the second string in the first string. The function should be case insensitive.
Example: indexOfIgnoreCase('bit','it') and indexOfIgnoreCase('bit','IT') should return 1.
Example: indexOfIgnoreCase('bit','it') and indexOfIgnoreCase('bit','IT') should return 1.
Answer:
function indexOfIgnoreCase (s1, s2) {
let x = s1.toLowerCase();
let y = s2.toLowerCase();
let z = x.indexOf(y);
return z;
let x = s1.toLowerCase();
let y = s2.toLowerCase();
let z = x.indexOf(y);
return z;
};
> function indexOfIgnoreCase has to perform two tasks
> it has to ignore the case (lower or upper) of both the strings
> it has to return the position of the first occurrence of a specified value in a string
> we first 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 final 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 return the value of z
> indexOf() method returns the position of the first occurrence of a specified value in a string.
> it is case sensitive
> returns -1 if the value to search for never occurs
No comments:
Post a Comment