Javascript if string contains text

How to check if a string contains a substring in JavaScript

There are multiple ways to check if a string contains a substring in JavaScript. You can use either String.includes() , String.indexOf() , String.search() , String.match() , regular expressions, or 3rd-party library like Lodash.

The String.includes() provides the most simple and popular way to check if a string contains a substring in modern JavaScript. It was introduced in ES6 and works in all modern browsers except Internet Explorer. The String.includes() method returns true if the string contains the specified substring. Otherwise, it returns false . Here is an example:

let str = 'MongoDB, Express, React, Node' str.includes('MongoDB') //true str.includes('Java') //false str.includes('Node') //true 

Note that includes() is case-sensitive and accepts an optional second parameter, an integer, which indicates the position where to start searching for.

let str = 'MongoDB, Express, React, Node' str.includes('express') // false (Due to case-sensitive) str.includes('React', 5) // true 

The String.indexOf() method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1 . The indexOf() method is case-sensitive and accepts two parameters. The first parameter is the substring to search for, and the second optional parameter is the index to start the search from (the default index is 0 ).

let str = 'MongoDB, Express, React, Node' str.indexOf('MongoDB') !== -1 // true str.indexOf('Java') !== -1 // false str.indexOf('Node', 5) !== -1 // true 

The String.search() method searches the position of the substring in a string and returns the position of the match. The search value can be a string or a regular expression. It returns -1 if no match is found.

let str = 'MongoDB, Express, React, Node' str.search('MongoDB') !== -1 // true str.search('Java') !== -1 // false str.search(/node/i) !== -1 // true where i is the case insensitive modifier 

The String.match() method accepts a regular expression as a parameter and searches the string for a match. If it finds the matches, it returns an object, and null if no match is found.

let str = 'MongoDB, Express, React, Node' str.match(/MongoDB/) // ['MongoDB', index: 0, input: 'MongoDB, Express, React, Node', groups: undefined] str.match(/Java/) // null str.match(/MongoDB/g) !== null // true str.match(/Java/g) !== null // false str.match(/node/i) !== null // true where i is the case insensitive modifier 

The RegExp.test() method executes a search for a match between a regular expression and a specified string. It returns true if it finds a match. Otherwise, it returns false .

let str = 'MongoDB, Express, React, Node' const exp = new RegExp('MongoDB', 'g') exp.test(str) // true /Java/g.test(str) // false /node/i.test(str) // true where i is the case insensitive modifier 

Lodash is a third-party library that provides _.includes() method to check the presence of a substring in a string. This method returns true if a match is found, otherwise, false .

let str = 'MongoDB, Express, React, Node' _.includes(str, 'MongoDB') // true _.includes(str, 'Java') // false _.includes(str, 'Node') // true 

You might also like.

Источник

JavaScript String includes()

The includes() method returns true if a string contains a specified string.

Otherwise it returns false .

The includes() method is case sensitive.

Syntax

Parameters

Parameter Description
searchvalue Required.
The string to search for.
start Optional.
The position to start from.
Default value is 0.

Return Value

More Examples

Browser Support

includes() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

includes() is not supported in Internet Explorer 11 (or earlier).

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

String.prototype.includes()

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

Синтаксис

str.includes(searchString[, position])

Параметры

Строка для поиска в данной строке.

Позиция в строке, с которой начинать поиск строки searchString , по умолчанию 0.

Возвращаемое значение

true , если искомая строка была найдена в данной строке; иначе false .

Описание

Этот метод позволяет вам определять, содержит ли строка другую строку.

Чувствительность к регистру символов

Метод includes() является регистрозависимым. Например, следующее выражение вернёт false :

'Синий кит'.includes('синий'); // вернёт false 

Примеры

Использование includes()

var str = 'Быть или не быть вот в чём вопрос.'; console.log(str.includes('Быть')); // true console.log(str.includes('вопрос')); // true console.log(str.includes('несуществующий')); // false console.log(str.includes('Быть', 1)); // false console.log(str.includes('БЫТЬ')); // false 

Полифил

Этот метод был добавлен в спецификации ECMAScript 2015 и может быть недоступен в некоторых реализациях JavaScript. Однако, можно легко эмулировать этот метод:

if (!String.prototype.includes)  String.prototype.includes = function(search, start)  'use strict'; if (typeof start !== 'number')  start = 0; > if (start + search.length > this.length)  return false; > else  return this.indexOf(search, start) !== -1; > >; > 

Спецификации

Поддержка браузерами

BCD tables only load in the browser

String.prototype.contains

В Firefox с версии 18 по версию 39, этот метод назывался «contains». Он был переименован в «includes» в замечании баг 1102219 по следующей причине:

Как было сообщено, некоторые сайты, использующие MooTools 1.2, ломаются в Firefox 17. Эта версия MooTools проверяет существование метода String.prototype.contains() и, если он не существует, добавляет свой собственный. С введением этого метода в Firefox 17, поведение этой проверки изменилось таким образом, что реализация String.prototype.contains() , основанная на MooTools, сломалась. В результате это изменение было отключено в Firefox 17. Метод String.prototype.contains() доступен в следующей версии Firefox — Firefox 18.

MooTools 1.3 принудительно использует свою собственную версию метода String.prototype.contains() , так что использующие его веб-сайты не должны ломаться. Тем не менее, следует отметить, что сигнатура метода в MooTools 1.3 отличается от сигнатуры метода в ECMAScript 2015 (во втором аргументе). В MooTools 1.5+ сигнатура изменена для соответствия стандарту ES2015.

В Firefox 48, метод String.prototype.contains() был удалён. Следует использовать только String.prototype.includes() .

Смотрите также

  • Array.prototype.includes() Экспериментальная возможность
  • TypedArray.prototype.includes() (en-US) Экспериментальная возможность
  • String.prototype.indexOf()
  • String.prototype.lastIndexOf()
  • String.prototype.startsWith()
  • String.prototype.endsWith()

Found a content problem with this page?

This page was last modified on 22 окт. 2022 г. by MDN contributors.

Источник

How to check if a string contains a substring in JavaScript

There are multiple ways to check if a string contains a substring in JavaScript. You can use either String.includes() , String.indexOf() , String.search() , String.match() , regular expressions, or 3rd-party library like Lodash.

The String.includes() provides the most simple and popular way to check if a string contains a substring in modern JavaScript. It was introduced in ES6 and works in all modern browsers except Internet Explorer. The String.includes() method returns true if the string contains the specified substring. Otherwise, it returns false . Here is an example:

let str = 'MongoDB, Express, React, Node' str.includes('MongoDB') //true str.includes('Java') //false str.includes('Node') //true 

Note that includes() is case-sensitive and accepts an optional second parameter, an integer, which indicates the position where to start searching for.

let str = 'MongoDB, Express, React, Node' str.includes('express') // false (Due to case-sensitive) str.includes('React', 5) // true 

The String.indexOf() method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1 . The indexOf() method is case-sensitive and accepts two parameters. The first parameter is the substring to search for, and the second optional parameter is the index to start the search from (the default index is 0 ).

let str = 'MongoDB, Express, React, Node' str.indexOf('MongoDB') !== -1 // true str.indexOf('Java') !== -1 // false str.indexOf('Node', 5) !== -1 // true 

The String.search() method searches the position of the substring in a string and returns the position of the match. The search value can be a string or a regular expression. It returns -1 if no match is found.

let str = 'MongoDB, Express, React, Node' str.search('MongoDB') !== -1 // true str.search('Java') !== -1 // false str.search(/node/i) !== -1 // true where i is the case insensitive modifier 

The String.match() method accepts a regular expression as a parameter and searches the string for a match. If it finds the matches, it returns an object, and null if no match is found.

let str = 'MongoDB, Express, React, Node' str.match(/MongoDB/) // ['MongoDB', index: 0, input: 'MongoDB, Express, React, Node', groups: undefined] str.match(/Java/) // null str.match(/MongoDB/g) !== null // true str.match(/Java/g) !== null // false str.match(/node/i) !== null // true where i is the case insensitive modifier 

The RegExp.test() method executes a search for a match between a regular expression and a specified string. It returns true if it finds a match. Otherwise, it returns false .

let str = 'MongoDB, Express, React, Node' const exp = new RegExp('MongoDB', 'g') exp.test(str) // true /Java/g.test(str) // false /node/i.test(str) // true where i is the case insensitive modifier 

Lodash is a third-party library that provides _.includes() method to check the presence of a substring in a string. This method returns true if a match is found, otherwise, false .

let str = 'MongoDB, Express, React, Node' _.includes(str, 'MongoDB') // true _.includes(str, 'Java') // false _.includes(str, 'Node') // true 

You might also like.

Источник

Читайте также:  Java creating temporary files
Оцените статью