Find if a string contains a substring in JavaScript!

This post will explain how to find a substring in a string using pure JavaScript. Let’s see how can we achieve this.

var str = 'testing';
var substr = 'tin';
alert(str.indexOf(substr) !== -1);

The above script will show an alert ‘true’ because sub-string ‘tin’ is present in the string ‘testing’. So basically to check a sub-string in JavaScript is to use indexOf()

Now, let’s see a full example of how to check this sub-string dynamically.

<!DOCTYPE html>
<html>
	<head>
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<script>
		function chkSubstr(){
			var str = 'testing';
			var substr = document.getElementById("substr").value;
			var res = str.indexOf(substr) !== -1;
			document.getElementById("result").innerHTML = res;
		}
	</script>
	</head>
	<body>
		<div class="container">
			<div class="row">
				<div class="form-group">
					<br />
					<div class="form-group">
						String: <label for="str">testing</label> 
					</div>
					<div class="form-group">
						<label for="substr">SubString:</label> 
						<input type="text" value="ing" class="form-control" id="substr">
					</div>
					<div class="form-group">
						<div><b>Result: </b><span id="result"></span></label>
					</div>
					<br />
					<button onClick="chkSubstr()" class="btn btn-default">Check</button>
				</div>
			</div>
		</div>
	</body>
</html>

See the demo here:

demo

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top