get string between two strings with javascript

Use this code

var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig"); //set ig flag for global search and case insensitive

var testRE = regExString.exec("My cow always gives milk.");
if (testRE && testRE.length > 1) //RegEx has found something and has more than one entry.
{  
    alert(testRE[1]); //is the matched group if found
}

This matches only the middle part of the sentence.

  1. (?:"+firstvariable+") finds but does not capture cow.
  2. (.*?) captures all characters between cow and milk and saves it in a group. ? makes it lazy so it stops at milk.
  3. (?:"+secondvariable+") finds but does not capture milk.

You can test this below:

function testString()
{
    var test = document.getElementById("testStringDiv").textContent;
    var firstvariable = document.querySelectorAll("input")[0].value; //first input;
    var secondvariable = document.querySelectorAll("input")[1].value; //second input;
    var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig");
    var testRE = regExString.exec(test);

    if (testRE && testRE.length > 1)
    {  
      document.getElementById("showcase").textContent = testRE[1]; //return second result.
    }
}
document.getElementById("test").addEventListener("click", testString, true);
<div id="testStringDiv">My cow always gives milk.</div>
<div id="showcase">Result will display here...</div>
<input placeholder="enter first var"/><input placeholder="enter second var"/><button id="test">Search in between...</button>

Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));