title: Javascript: Find every instance of strings between two strings
body: <p>I have a string which contains a word encased in @- and -@ like so: This @-book-@ is created by author @-gameauthor-@.</p>
  
  <p>I need a function that will find all the instances of words in between that encasement and return it. It works well if there is only one word encased in it. But if there are two words it will return everything in between the first @- and the last -@. So instead of returning book and gameauthor, it returns: -book-@ is created by author @-gameauthor-</p>
  
  <p>I wrote this function and code, how can I improve it:</p>
  
  <pre><code>function findBetween(text, firststring, secondstring) {
  
  
      //Function to text between two strings.
      var firstvariable = firststring;
      var secondvariable = secondstring;
      var text = text;
  
      var regExString = new RegExp("(?:" + firstvariable + ")((.[\s\S]*))(?:" + secondvariable + ")", "g"); 
  
      var strResult = regExString.exec(text);
  if (strResult != null) {
      return strResult[1];
      }
  }
  
  var str = "This @-book-@ is created by author @-gameauthor-@.";
  
  var test = findBetween(str, "@-", "-@");
  
  alert(test);
  </code></pre>
  
  <p>EDIT: Here is an updated code using the solution below:</p>
  
  <pre><code>function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
  }   
  
  var book = "Moby Dick";
  var gameauthor = "Joey DiPerla";
  
  var str = "This @-book-@ is created by author @-gameauthor-@.";
  
  var myArray = str.split("@");
  
  var len = myArray.length;
  
  for(let i = len-1;i&gt;=0;i--){  
     myArray[i] = myArray[i].replace(/-/g, '');
     if(i%2 == 0) {
         myArray.splice(i,1)
  
      if ( myArray[i] !== undefined) {
  
          var find = "@-" + myArray[i] + "-@";
          var replace = eval(myArray[i]);
  
          str = replaceAll(str, find, replace);
      }
  
     }
  }
  
  alert(str);
  </code></pre>