Home » JavaScript

How to check whether a string contains a substring in JavaScript?

In this example, we are going to learn how to check whether a string contains a substring or not in JavaScript?
Submitted by IncludeHelp, on February 14, 2019

Given a string, substring and we have to check whether a string contains a substring or not?

Checking string contains substring or not

There are two popular ways to check whether a substring exists in a string or not?

  1. Using JavaScript includes() method
  2. Using JavaScript indexOf() method

1) Using JavaScript includes() method

includes() method is a string method in JavaScript, it returns true if the string contains a substring or not?

Syntax:

    string.includes(substring);

JavaScript Code to check whether a string contains a substring or not using includes() method:

<script>
	var str = "Hello world!";
	var substr = "Hello";
	if(str.includes(substr)==true){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}

	substr = "Okay";
	if(str.includes(substr)==true){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}		
</script>

Output

Hello world! contains Hello
Hello world! does not contain Okay

2) Using JavaScript indexOf() method

indexOf() is a string method in JavaScript, if substring founds in the string - it returns the starting position of the substring if substring does not found in the string – it returns -1.

Syntax:

    string.indexOf(substring);

JavaScript Code to check whether a string contains a substring or not using indexOf() method:

<script>
	var str = "Hello world!";
	var substr = "Hello";
	if(str.indexOf(substr) != -1){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}

	substr = "Okay";
	if(str.indexOf(substr) != -1){
		document.write(str + " contains " + substr + "<br>");
	}
	else{
		document.write(str + " does not contain " + substr + "<br>");
	}		
</script>

Output

Hello world! contains Hello
Hello world! does not contain Okay





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.