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

Share This Post

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.

Example:

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related Posts

Meta to face a trademark lawsuit over its infinity-symbol logo

The rebranding or transformation of Facebook to Meta has...

45+ Happy Labor Day Wishes, Messages, Greetings and Quotes

Labor Day, also known as International Workers Day, is...

Android Users: How to add songs from Youtube Music to Snapchat

Snapchat has begun to roll out a feature that...

4 Easy ways to get unbanned from Omegle

If you enjoy chatting on the platform Omegle, you...

Fix “running as root without –no-sandbox” Error in Puppeteer

The Google Dev Team's Puppeteer is a strong tool...

Tips for enhancing the FaceTime call experience on iPhone, iPad, and Mac

With the introduction of iOS 15 and macOS Monterey...
spot_img
- Advertisement -spot_img