jQuery Check if String Contains Specific Word in JavaScript

Introduction

Here I will explain how to use
jQuery to check particular word in string in JavaScript or jQuery to check if string contains specific word in JavaScript.
Description:
  
In previous articles I explained jQuery add border to images in webpage, jQuery show loading image in pageload, jQuery hide div elements after 5 seconds, jQuery convert am / pm time to 24 hours time, jQuery print div content with css
and many articles relating to JQuery, JavaScript. Now I will explain how to check if string contains specific word in JavaScript.

To check particular word in string we need to write code like as shown below
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Check Particular word in string in JavaScript</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$('#btnCheck').click(function() {
var str = 'how are you';
var txt = $('#txtword').val();
if (str.indexOf(txt) > -1) {
alert('String Contains Word');
return true;
} else {
alert('String Does not contains word');
return false;
}
});
})
</script>
</head>
<body>
<div>
Check word in this String: <b>How are You</b><br />
Enter Text to Search: <input type="text" id="txtword" value="how" />
<input type="button" id="btnCheck" value="Check" />
</div>
</body>
</html>

Comments