This post will explain how to find a substring in a string using pure JavaScript. Let’s see how can we achieve this.
1 2 3 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!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: