String search() Method with Example in JavaScript

JavaScript String search() Method: Here, we are going to learn about the search() method of String in JavaScript.
Submitted by IncludeHelp, on February 02, 2019

String search() Method

search() is method is a String method, it is used to check whether a substring exists in the given string or not. It returns the starting index of the substring from the string where substring exists. If substring does not exist in the string – it returns -1.

Syntax:

    String.search(substring);

Here, substring is the part of the string to be searched.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
<script>		
	var str = "friends say Hello";
	
	var substr = "Hello";		
	var index = str.search(substr);
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");

	substr = "Hi";
	index = str.search(substr);		
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");	
</script>
</body>
</html>

Output

Hello found at 12 position.
Hi does not exist in the friends say Hello.

JavaScript String Object Methods »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.