Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
June 24, 2024
In JavaScript, you can check whether a string contains a substring using several methods. Here are some common approaches:
The indexOf() method returns the index within the string of the first occurrence of the specified substring, or -1 if the substring is not found.
Example:
const str = 'Hello, world!'; const substring = 'world'; if (str.indexOf(substring) !== -1) { console.log('Substring found'); } else { console.log('Substring not found'); }
The includes() method determines whether a string contains the specified substring. It returns true if the substring is found, otherwise false.
Example:
const str = 'Hello, world!'; const substring = 'world'; if (str.includes(substring)) { console.log('Substring found'); } else { console.log('Substring not found'); }
You can also use regular expressions to check for substrings within a string.
Example:
const str = 'Hello, world!'; const substring = 'world'; const regex = new RegExp(substring); if (regex.test(str)) { console.log('Substring found'); } else { console.log('Substring not found'); }