By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Find String within another String With JavaScript

How to find a needle in a haystack with JavaScript.

Edited: 2015-04-01 16:41

A fairly common task, is perhaps, to locate a string inside another string. This can either be a single word, a sequence of words, or just random characters. In JavaScript, one way to do it, is to use the indexOf() function, but you could also use regular expressions if it suits your needs better.

Regular expressions are perfect to work with HTML, finding a link in the HTML source code, or selecting certain patterns. They are often used to validate user-input, to prevent unnecessary server-sided validation, which can take up a lot of resources on high-traffic sites.

The indexOf() function is better suited for simple things, like finding a needle in a haystack, checking whether a string exists inside another. For those who do not need the explanation, the example is included below:

var str = "This string contains a needle";
var n = str.indexOf("needle");

if (n >= 1) {
  alert("Found");
} else {
  alert("Not Found");
}

String in String with indexOF

Using indexOf() is a lot easier than using regular expressions, so this is what we will focus on first in this tutorial. The indexOf() function checks a string to see if it contains a substring, and then returns the numeric position of the first character of the substring, if the string contains the substring.

Or explained with the needle in haystack saying, the function will look for needle in haystack, and return the numeric location of needle – that is the first character of needle – inside of haystack. Knowing this, we can then respond accordingly, using a if statement to check whether needle was found or not.

<!DOCTYPE html>
<html>

  <body>
    <p>The area below is editable, try pushing the button before and after changing its content.</p>

    <div style="border: 1px solid #000;margin:1em 0;width:400px;height:1.2em;padding:0.5em;border-radius:5px;" id="myinput" contenteditable>This haystack has a needle</div>
    <button onclick="myFunction()">Check input</button>
	<p id="TheResult"></p>
	
    <script>
    function myFunction() {
      var str = document.getElementById("myinput").innerHTML;
      var n = str.indexOf("needle");
        document.getElementById("TheResult").innerHTML = n;
    }
    </script>
  </body>
</html>

Handling the result

When the string you are looking for is found, you might want to do something with the string. The value returned by indexOf() can be handled with a simple if statement. Below we simply return the position of the substring in a JavaScript alert – you can easily make your own modifications to this function.

function myFunction() {
  var str = document.getElementById("myinput").innerHTML;
  var n = str.indexOf("needle");

  if (n >= 1) {
    alert("Found: " + n);
  } else {
    alert("Not Found");
  }
}

Since the result will always return a numeric value, and -1 when nothing is found, we can simply do a Greater than or Equal to comparision, to check whether the substing was found within the string.

Another way of comparison is the Not Equal To (!=) operator, which would make the statement look like:

if (n != -1) {
  alert("Found");
} else {
  alert("Not Found");
}