36

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.

Community
  • 1
  • 1
user3080392
  • 1,194
  • 5
  • 18
  • 35
  • 1
    How should it handle a case like "My cow gives milk. I like milk". Should the match be not greedy: "cow gives milk" or greedy: "cow gives milk. I like milk"? – RobG Dec 26 '14 at 11:40
  • If you're gonna down vote, you could at least give a reason why. – user3080392 Dec 26 '14 at 12:22

2 Answers2

55

Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
myTerminal
  • 1,596
  • 1
  • 14
  • 31
  • 10
    It returns two parameters, and the fist is the full string – Pini Cheyni Oct 26 '16 at 14:52
  • The result is an `Array` (or `null` if no match). There may be multiple matches depending on RegExp and tested text. The result contains 1.) **all matching results** and 2.) **each matching group** (parts matching regexp in parentheses). E.g.: `"xxxxABCDEFxxxxx".match(new RegExp( "AB(CD)(EF)" ))` returns ["ABCDEF","CD","EF"] – Fenix Jul 28 '21 at 19:31
  • 1
    Note 2: It is a greedy match (its result is the **longest matching string**). E.g.: "xxxxAAmCCmCCmCCxxxx".match(new RegExp( "AA(.*)CC" )) returns ["AAmCCmCCmCC","mCCmCCm"]. – Fenix Jul 28 '21 at 19:44
  • How it works if string contains '\n' at middle? – 151291 Dec 21 '21 at 06:25
  • To make this non greedy so it matches the first instance instead then change "(.*)" to "(.*?)", so the full thing would be: test.match(new RegExp(firstvariable + "(.*?)" + secondvariable)); – tay Feb 07 '22 at 16:38
12

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>
Mouser
  • 13,132
  • 3
  • 28
  • 54