Поиск строк в JavaScript


Оглавление

    Показать оглавление

Методы поиска строк

  • String indexOf()
  • String lastIndexOf()
  • String search()
  • String match()
  • String matchAll()
  • String includes()
  • String startsWith()
  • String endsWith()

Строка JavaScript indexOf()

Метод indexOf() возвращает индекс (позицию). первое вхождение строки в строку:

Пример

let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>The indexOf() method returns the position of the first occurrence of a string in a string.</p>
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

Примечание

JavaScript считает позиции с нуля.

0 — первая позиция в строка, 1 — вторая, 2 — третья,...


Строка JavaScript LastIndexOf()

Метод lastIndexOf() возвращает индекс последнего появление указанного текста в строке:

Пример

let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The lastIndexOf() Method</h2>

<p>The position of the last occurrence of "locate" is:</p>

<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

И indexOf(), и lastIndexOf() возвращают -1 если текст не найден:

Пример

let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>Both indexOf() and lastIndexOf() return -1 if the text is not found:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("John");
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

Оба метода принимают второй параметр в качестве начальной позиции для поиск:

Пример

let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>The indexOf() method accepts a second parameter as the starting position for the search:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate",15);
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

Методы lastIndexOf() выполняют поиск в обратном направлении. (от конца к началу), что означает: если второй параметр равен 15, поиск начинается с позиции 15 и выполняет поиск до начала строки.

Пример

let text = "Please locate where 'locate' occurs!";
text.lastIndexOf("locate", 15);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The lastIndexOf() Method</h2>

<p>The lastIndexOf() method accepts a second parameter as the starting position for the search.</p>
<p>Remember that the lastIndexOf() method searches backwards, so position 15 means start the search at position 15, and search to the beginning.</p>

<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate", 15);
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>


Поиск строки JavaScript()

Метод search() ищет в строке строку (или регулярное выражение). и возвращает позицию совпадения:

Примеры

let text = "Please locate where 'locate' occurs!";
text.search("locate");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The search() Method</h2>

<p>The search() method returns the position of the first occurrence of a string in a string.</p>
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.search("locate");
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

let text = "Please locate where 'locate' occurs!";
text.search(/locate/);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The search() Method</h2>

<p>The search() method returns the position of the first occurrence of a string in a string.</p>
<p>Return the position of the first occurrence of a regular expression:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.search(/locate/);
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>


Ты заметил?

Два метода, indexOf() и search(), равны?

Они принимают одни и те же аргументы (параметры) и возвращают одно и то же значение?

Эти два метода НЕ равны. Вот различия:

  • Метод search() не может принимать второй аргумент начальной позиции.

  • Метод indexOf() не может принимать мощные значения поиска (регулярные выражения).

Вы узнаете больше о регулярные выражения в одной из следующих глав.



Сопоставление строк JavaScript()

Метод match() возвращает массив, содержащий результаты сопоставления. строка против строки (или регулярного выражения).

Примеры

Выполните поиск по слову «айн»:

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match("ain"); 

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain";
const myArr = text.match("ain");
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Выполните поиск по слову «айн»:

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/); 

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;

</script>

</body>
</html>

Выполните глобальный поиск по слову «ain»:

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/g); 

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a global search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/g);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Выполните глобальный поиск «ain» без учета регистра:

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/gi);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a global, case-insensitive search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/gi);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Примечание

Если регулярное выражение не содержит модификатор g (глобальный поиск), match() вернет только первое совпадение в строке.

Подробнее о регулярных выражениях читайте в главе JS RegExp.


Строка JavaScript matchAll()

Метод matchAll() возвращает итератор, содержащий результаты сопоставления. строка против строки (или регулярного выражения).

Пример

const iterator = text.matchAll("Cats");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll("Cats");

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Если параметр является регулярным выражением, должен быть установлен глобальный флаг (g), в противном случае выдается TypeError.

Пример

const iterator = text.matchAll(/Cats/g);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll(/Cats/g);

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Если вы хотите выполнять поиск без учета регистра, необходимо установить флаг нечувствительности (i):

Пример

const iterator = text.matchAll(/Cats/gi);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll(/Cats/gi);

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Примечания

matchAll() — это функция ES2020.

matchAll() не работает в Internet Explorer.


Строка JavaScript включает()

Метод includes() возвращает значение true, если строка содержит указанное значение.

В противном случае возвращается false.

Примеры

Проверьте, содержит ли строка «мир»:

let text = "Hello world, welcome to the universe.";
text.includes("world");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>

<p>Check if a string includes "world":</p>
<p id="demo"></p>

<p>The includes() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world");
</script>

</body>
</html>

Проверьте, содержит ли строка слово «мир». Начните с позиции 12:

let text = "Hello world, welcome to the universe.";
text.includes("world", 12);

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>

<p>Check if a string includes "world" starting from position 12:</p>
<p id="demo"></p>

<p>The includes() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world", 12);
</script>

</body>
</html>

Примечания

includes() чувствителен к регистру.

includes() — это функция ES6.

includes() не поддерживается в Internet Explorer.


Строка JavaScript начинается с()

Метод startsWith() возвращает true если строка начинается с указанного значения.

В противном случае возвращается false:

Примеры

Возвращает истину:

let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>
<p>Check if a string starts with "Hello":</p>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("Hello");
</script>

</body>
</html>

Возвращает ложь:

let text = "Hello world, welcome to the universe.";
text.startsWith("world")

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world");
</script>

</body>
</html>

Начальную позицию поиска можно указать:

Возвращает ложь:

let text = "Hello world, welcome to the universe.";
text.startsWith("world", 5)

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 5);
</script>

</body>
</html>

Возвращает истину:

let text = "Hello world, welcome to the universe.";
text.startsWith("world", 6)

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 6);
</script>

</body>
</html>

Примечания

startsWith() чувствителен к регистру.

startsWith() — это функция ES6.

startsWith() не поддерживается в Internet Explorer.


Строка JavaScript заканчивается с()

Метод endsWith() возвращает true если строка заканчивается указанным значением.

В противном случае возвращается false:

Примеры

Проверьте, заканчивается ли строка на «Doe»:

let text = "John Doe";
text.endsWith("Doe");

Попробуйте сами →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Check if a string ends with "Doe":</p>

<p id="demo"></p>

<p>The endsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "John Doe";
document.getElementById("demo").innerHTML = text.endsWith("Doe");
</script>

</body>
</html>

Проверьте, заканчиваются ли 11 первых символов строки словом «мир»:

let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);

Попробуйте сами →

Примечания

endsWith() чувствителен к регистру.

endsWith() — это функция ES6.

endsWith() не поддерживается в Internet Explorer.


Полная ссылка на строку

Для получения полной справки по строкам перейдите по ссылке:

Полное руководство по строкам JavaScript.

Справочник содержит описания и примеры всех строковых свойств и методов.