How to check if a string exists in a string in JavaScript?

In this tutorial I have created a function in JavaScript for checking if a String contains in a String or not?

How to check if a string exists in a string in JavaScript?

How to check if a string exists in a string in JavaScript?

JavaScript function given in this tutorial can be used to find the existence of String inside a String in JavaScript. Function takes two parameters source string and the string to be searched for. Function returns true if it founds the given string in source string or returns false if it does not found the string in the source string.

We have also created a video tutorial, which explains the steps to check the example function. In this video tutorial we have explained the methods and the use of the function defined here.

To use the function you have to call this function by passing the two parameters e.g. source string and the string to be searched. Then function returns true or false value.

You can use this JavaScript function in your program to check if a string exists in a string in JavaScript.

Here is the video tutorial “How to check if a string exists in a string in JavaScript?”:

Here is the video tutorial of "How to check if a string exists in a string in JavaScript?":

Function for checking the existence of a string in source string:

function ifExists(content,contentToFind ){	
	//Find in the String
	var result = result = (content.indexOf(contentToFind) > -1) ? true : false;
	//Print result
	return result;
}

Here is the complete source code of the HTML program:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>JavaScript Example</title>
  <script language="JavaScript">
	function ifExists(content,contentToFind ){
		
	//Find in the String
	var result = result = (content.indexOf(contentToFind) > -1) ? true : false;
	//Print result
	return result;

	}
	
	function findContent(){
	var content  = document.testform.txtcontent.value;
	var contentToFind  = document.testform.txtfindstring.value;
	if(ifExists(content,contentToFind )){
		alert("Content found");
	}else{
		alert("Content not found");
	}
	}

  </script>
 </head>

 <body>
  <form id="testform" name="testform">
	<p>Content: <input type="text" name="txtcontent" 
      id="txtcontent" value="Rose India Technologies Pvt. Ltd." >
	</p>
	<p>Find String: <input type="text" name="txtfindstring" id="txtfindstring" ></p>
	<p><input type="button" value="Search in content" onclick="findContent()"></p>
  </form>
 </body>
</html>

Check more tutorials of JavaScript in our JavaScript tutorials section.

Click Download Source Code