+ 3
[ Solved ] Why, the following code's output is 7?
let str = "Locate Me"; let outPut = str.indexOf("M", 4); console.log(outPut);
9 Answers
+ 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 </>