+ 3
[ Solved ] Why, the following code's output is 7?
let str = "Locate Me"; let outPut = str.indexOf("M", 4); console.log(outPut);
14 Respostas
+ 5
â€âąâ đđąđąđđš đđĄđđČđđ„ ââąâ€ thanks bro, I've understood đ
+ 4
â€âąâ đđąđąđđš đđĄđđČđđ„ ââąâ€ But I used second parameter đ
+ 3
Yes now I completely understand! Thank you â€âąâ đđąđąđđš đđĄđđČđđ„ ââąâ€
+ 3
IndexOf() is used to return the index(position or location) of the first occurance a specified character or string and the indexing starts from 0, including spaces. So in 'Locate Me', M's index is 7.
+ 3
Because the first occurance of "M" starting with the fifth character (t) is the 7th index (8th character) đ€
+ 2
â€âąâ đđąđąđđš đđĄđđČđđ„ ââąâ€ then, shouldn't the output has to be 3 or 4?
+ 2
â€âąâ đđąđąđđš đđĄđđČđđ„ ââąâ€ so you are telling that, it starts searching from specified value but count positions from zero?
+ 2
Abir Sheikh the second parameter only specifies the index position of where you should start the search for the position of the first occurence of the value.
It does not change the index positions.
Here is an example:
let str = "money made";
let output = str. indexOf("m") ;
console.log(output); // 0
let output2 = str. indexOf("m", 4) ;
console.log(output2);// 6
Hope this helps.
+ 2
It is because the indexOf() method returns the position of the first occurrence of a specified value in a string.
String.indexOf(searchvalue, start)
Your second parameter tells you at which position to start the search. It's default value is 0.
I hope you understood đ
đ
đ
L o c a t e m e
0 1 2 3 4 5 6 7 8
Hope it helped !
Happy Coding </>