How to Check if String Contains Substring in JavaScript
Table of Contents
When you are working with strings, you might want to know if a string contains a substring.
Maybe we need to check if a string is in the right format or contains the right characters.
Either way, in this post, we'll learn the best ways in which you can check if a string contains a substring in JavaScript.
Using includes()
The best way one can check if a string contains a substring is to utilize the includes()
method.
This built-in function on the String
object checks if a string contains a substring.
It takes a substring as an argument and returns a boolean value, which is exactly what we need.
Here's an example of how to use the includes()
method:
JAVASCRIPTconst string = "Hello World";
const contains = string.includes("World");
console.log(contains); // true
Using indexOf()
Another way you can check if a string in JavaScript contains a substring is to utilize the indexOf()
method.
This function instead returns the index of the first occurrence of the substring in the string.
From there, we can check if the index is greater than -1
because if it is, then the substring was found.
Here's how to use the indexOf()
method to check if a string contains a substring:
JAVASCRIPTconst string = "Hello World";
const contains = string.indexOf("World") > -1;
console.log(contains); // true
If the string doesn't contain the substring, then the index will be -1
.
Conclusion
In this post, we looked at the best ways in which you can check if a string contains a substring in JavaScript.
The first method uses the includes()
method, and the second method uses the indexOf()
method.
Hopefully, this post has been useful to you. Thanks for reading!
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue