How to check whether a string contains a substring in JavaScript?
Javascript | string | substring | indexOf | includes | how to
Graduated with a Master’s degree in Software Engineering from San Jose State University in December 2019 and currently working at PayPal on the Customer Journey Platform. I enjoy generating new ideas and devising feasible solutions to broadly relevant problems. My colleagues would describe me as a driven, resourceful individual who maintains a positive, proactive attitude when faced with adversity. Interested to work in areas related to Distributed Systems, Cloud Infrastructure and Micro-Services. I get a lot of satisfaction from the constant learning and puzzle solving that comes with my profession and contributing to a successful and worthwhile product. My expertise includes project design and management, data analysis and interpretation, and the development and implementation of software products.
ECMAScript 6 introduced String.prototype.includes:
const string = "Hello World!";
const substring = "World";
console.log(string.includes(substring)); // true
Note: includes doesn’t have Internet Explorer support. In ECMAScript 5 or older environments, use String.prototype.indexOf, which would return -1 when a substring cannot be found:
var string = "Hello World!";
var substring = "Hello";
console.log(string.indexOf(substring) !== -1); // true
includesandindexOfperforms a case-sensitive search