Пример 1. Методы indexOf и lastIndexOf используются для локализации значений в строке "Brave new world."
var anyString="Brave new world"// Выводит 8 document.write("<P>The index of the first w from the beginning is " + anyString.indexOf("w")) // Выводит 10 document.write("<P>The index of the first w from the end is " + anyString.lastIndexOf("w")) // Выводит 6 document.write("<P>The index of 'new' from the beginning is " + anyString.indexOf("new")) // Выводит 6 document.write("<P>The index of 'new' from the end is " + anyString.lastIndexOf("new"))
Пример 2. В этом примере определены две строковые переменные. Они содержат одинаковые строки, но вторая строка содержит символы в верхнем регистре. Первый метод writeln выводит 19. Поскольку метод indexOf учитывает регистр символов, строка "cheddar" не найдена в строке myCapString, поэтому второй метод writeln выведет -1.
myString="brie, pepper jack, cheddar" myCapString="Brie, Pepper Jack, Cheddar" document.writeln('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")) document.writeln('<P>myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"))
Пример 3. Здесь в count устанавливается количество вхождений буквы x в строке str: