如何使用与变量匹配的两个字符串之间获取字符串?如果我使用匹配字符串Regular Expression to get a string between two strings in Javascript,则以下代码效果很好我还尝试在JavaScript - Use variable in string match处应用信息:
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
但如果我有:
var firstvariable = "cow";
var secondvariable = "milk";
var test = "My cow always gives milk";
我尝试过各种各样的事情,包括:
var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);
和
var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);
都没有奏效。
答案 0 :(得分:23)
试试这个:
test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
答案 1 :(得分:11)
使用此代码
var regExString = new RegExp("(?:"+firstvariable+")(.*?)(?:"+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
}
这只匹配句子的中间部分。
(?:"+firstvariable+")
找到但未捕获cow
。(.*?)
捕获cow
和milk
之间的所有字符,并将其保存在一个组中。 ?
让它变得懒惰,所以它停在牛奶上。(?:"+secondvariable+")
找到但未捕获milk
。您可以在下面测试:
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+")(.*?)(?:"+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>
&#13;