Use this code
const regExString = new RegExp(`(?<=${firstVariable}).*?(?=${secondVariable})`, "ig"); //set ig flag for global search and case insensitive
const testRE = regExString.exec("My cow always gives milk.");
if (testRE && testRE.length > 0) //RegEx has found something and has at least one entry.
{
alert(testRE[0]); //is the matched group if found
}
This matches only the middle part of the sentence.
(?<="+firstvariable+") finds but does not capture cow :: lookbehind is possible now.
.*? captures all characters between cow and milk and saves it in a group. ? makes it lazy so it stops at milk.
(?="+secondvariable+") finds but does not capture milk. :: lookahead
You can test this below:
const test = document.getElementById("testStringDiv").textContent;
let firstVariable = "";
let secondVariable = "";
function testString()
{
firstVariable = document.querySelectorAll("input")[0].value; //first input;
secondVariable = document.querySelectorAll("input")[1].value; //second input;
//build the regex:
//lookbehind is possible in JavaScript now: (?<=) sees if the content in the matched group is preceded by the first variable, but does not capture this.
//for the second variable we use the (?=) which is a lookahead and does the same as the lookbehind.
//If there is a match, the string returned will be the one in the captured group (.*?)
let regExString = new RegExp(`(?<=${firstVariable}).*?(?=${secondVariable})`, "ig");
const testRE = regExString.exec(test);
if (testRE && testRE.length > 0)
{
document.getElementById("showcase").textContent = testRE[0]; //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>