问题
How do I get a string between two strings using match with variables? The following code works well if I use match with strings Regular Expression to get a string between two strings in Javascript I also tried to apply the info at JavaScript - Use variable in string match :
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
But what if I have:
var firstvariable = "cow";
var secondvariable = "milk";
var test = "My cow always gives milk";
I've tried various things including:
var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);
and:
var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);
Neither worked.
回答1:
Try this:
test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
回答2:
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.
(?:"+firstvariable+")finds but does not capturecow.(.*?)captures all characters betweencowandmilkand saves it in a group.?makes it lazy so it stops at milk.(?:"+secondvariable+")finds but does not capturemilk.
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>
来源:https://stackoverflow.com/questions/27656575/get-string-between-two-strings-with-javascript