title: JavaScript - Check which child string occurs first in a parent string using string.indexOf()
body: <p>I have a really long "parent" string (about 2,000 characters).<br/>
  I want to find out which of two "child" strings (or substrings) occur first.
  So far I've been using <code>string.indexOf()</code>:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>/* VARIABLES */
  var parentString = "Lorem foo ipsum dolor sit bar amet, consectetur adipiscing elit,..."
  
  var firstSubstring = "foo"
  var secondSubstring = "bar"
  
  var firstSubstringLength = firstSubstring.length
  var secondSubstringLength = secondSubstring.length
  
  var searchIndex = 0
  var continuationIndex = 0
  
  /* SEARCH FOR SUBSTRINGS */
  
  // Check if the substring exists
  if (parentString.indexOf(firstSubstring, searchIndex) &gt; -1) {
    console.log("firstSubstring occurred first in the ParentString")
    // Make the compiler continue its search from the end of firstSubstring"
    searchIndex = parentString.indexOf(firstSubstring, continuationIndex)
    continuationIndex = searchIndex + firstSubstringLength
  }
  // Check if the substring exists
  if (parentString.indexOf(secondSubstring, searchIndex) &gt; -1) {
    console.log("secondSubstring occurred second in the ParentString")
    // Make the compiler continue its search from the end of secondSubstring"
    searchIndex = parentString.indexOf(secondSubstring, continuationIndex)
    continuationIndex = searchIndex + secondSubstringLength
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>In a scenario where <code>secondSubstring</code> occurred in the <code>parentString</code> first, this code would still output that <code>firstSubstring</code> occurred first (because of the way this code is structured).<br/><br/>
  Is there a way to scan for both variables simultaneously and return the one which occurs first?.<br/>Thanks in advance!</p>