使用javascript在两个字符串之间获取字符串

use*_*392 21 javascript regex string

如何使用与变量匹配在两个字符串之间获取字符串?如果我使用匹配字符串正则表达式来获取Javascript中的两个字符串之间的字符串 我也尝试在JavaScript中应用信息- 在字符串匹配中使用变量:

var test = "My cow always gives milk";

var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)

但如果我有:

var firstvariable = "cow";
var secondvariable = "milk";

var test = "My cow always gives milk";
Run Code Online (Sandbox Code Playgroud)

我尝试过各种各样的事情,包括:

var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)

和:

var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);
Run Code Online (Sandbox Code Playgroud)

都没有奏效.

myT*_*nal 28

试试这个:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
Run Code Online (Sandbox Code Playgroud)

  • 它返回两个参数,第一个是完整的字符串 (4认同)

Mou*_*ser 12

使用此代码

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
}
Run Code Online (Sandbox Code Playgroud)

这只匹配句子的中间部分.

  1. (?:"+firstvariable+")发现但没有捕获cow.
  2. (.*?)捕获所有字符之间cow,并milk和一组保存它.?让它变得懒惰所以它停在牛奶上.
  3. (?:"+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);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)