How to Check if a String Contains a Substring in Javascript?

Multiple functions for manipulating and verifying cases against strings are available in all current programming languages.

These native functions are referred to as prototypes in JavaScript.

Using the JavaScript language, you may check if a string contains another string by using the easy one-liner below.

A substring is a string that is contained within another string.

It is possible to check if a string does not contain a substring using the indexOf() method.

The indexOf() method returns the position of the first occurrence of a string within another string. If the substring is not found, then it will return -1.


var name = “John”;

var age = “27”;

var howOld = name.indexOf(“age”); //1

How do you check if the string does not contain a substring in JavaScript?

There are two options for accomplishing this. All current browsers will support the first technique.

ES6 Method for Modern Browsers

var string = "hello"; var substring = lo"; if (string.includes(substring)) { console.log('string contains substring'); }

ES5 Method for Internet Explorer and Older Browsers

var string = "hello"; var substring = lo"; if (string.indexOf(substring) !== -1) { console.log('string contains substring'); }

Using native Javascript prototypes, that’s all there is to verify if strings have substrings.



Related articles

OnePlus 5T Wallpapers Download

Introduction: The OnePlus 5T is a popular smartphone known for...

Airtel’s First Quarterly Loss in 2002: A Closer Look at Jio’s Impact

The telecom industry has witnessed several significant shifts over...

Xiaomi Confirms Investment in Blackshark Gaming Phone Launch set for April 13

An engaging introduction to Xiaomi Confirms Investment in Blackshark...

LG G7 ThinQ M LCD Panel

Introduction:The LG G7 ThinQ M LCD panel is a...

Intel Core i9 Laptops with Optane Memory

Intel Core i9 laptops with Optane Memory combine the...

Apple iOS 11.4 Beta 1

Apple iOS 11.4 Beta 1 is the latest update...

Google Search AI Reorganization: Improving Search Quality and User Experience

Introduction:In the ever-evolving digital landscape, search engines play a...
Peter Graham
Peter Graham
Hi there! I'm Peter, a software engineer and tech enthusiast with over 10 years of experience in the field. I have a passion for sharing my knowledge and helping others understand the latest developments in the tech world. When I'm not coding, you can find me hiking or trying out the latest gadgets.


Please enter your comment!
Please enter your name here