JavaScript String Search

You can search a word or even a string from a string through search method of string object in JavaScript. Search method required a string parameter to make search on the string. You can also make search on the basis of regular expression. You can pass regular expression as an argument to search method. The search method returns the index value of the string which you are searching if it found in the string and if searched string does not found then it returns -1. The example of search method mentioned below: Code


<html>
  <head>
    <title>Search Method Example</title>
  </head>

  <body>
    <script language='JavaScript' type='text/JavaScript'>
      var weekDaysString = 'Sunday,Monday,Tuesday,Wednesday,Thursday,
      Friday,Saturday';
      var result = weekDaysString.search('Tuesday');
      if(result != -1){
      	alert('Your string is found.');	
      } else {
      	alert('Your string is not found.');
      }
    </script>
  </body>
</html>
In above mentioned example we have a string object with the name of weekDaysString and we make a search with search method and try to find the 'Tuesday' string, and store the result in result variable. We have also write a if conditional statement which show an alert message that "Your string is found." if string found elseif string does not found then show a message that "Your string is not found". You can also make search on the basis of regular expression. You can pass regular expression as an argument instead of string value. Syntax mention below:

Code

yourStringObject.search(regularExpression);