This code, taken from javascript.ru , searches for all occurrences of the substring "ia":
var str="ΠΡΠ»ΠΈΠΊ ΠΈΠ°-ΠΈΠ° ΠΏΠΎΡΠΌΠΎΡΡΠ΅Π» Π½Π° Π²ΠΈΠ°Π΄ΡΠΊ"; var poisk="ΠΈΠ°"; var i=0; do { var x = str.indexOf(poisk,i); i=x+1; alert(x) } while (x!=-1) The disadvantage of this code is that it goes through one extra iteration when indexOf has already returned -1 . I modified this code as follows:
var string = "JavaScript ΠΈ Java - ΡΠ°Π·Π½ΡΠ΅ ΡΠ·ΡΠΊΠΈ!"; var substring = "Java"; var nextDesiredSubstringPosition = 0; while (desiredSubstringPosition!=-1){ // ΠΏΠΎΠ·ΠΈΡΠΈΡ ΠΏΠΎΠ΄ΡΡΡΠΎΠΊΠΈ, ΠΊΠΎΡΠΎΡΡΡ ΠΌΡ ΠΈΡΠΌΠ΅ΠΌ var desiredSubstringPosition = string.indexOf(substring, nextDesiredSubstringPosition); if (desiredSubstringPosition === -1 ){break;} nextDesiredSubstringPosition = desiredSubstringPosition + 1;// Π² ΡΠ»Π΅Π΄ΡΡΡΠ΅ΠΉ ΠΈΡΠ΅ΡΠ°ΡΠΈΠΈ Π½Π°ΡΠΈΠ½Π°Π΅ΠΌ ΠΎΡΡΡΠ΄Π° } I removed the extra iteration, but it turns out that the condition while while never executed in the line with this condition, and the exit from the loop is done by nesting if . The program works, but the code is not logical. Is it possible to remove this inconsistency without complicating the code?