user3080392 user3080392 - 1 year ago 104
Javascript Question

get string between two strings with javascript

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");

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");


var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';

Neither worked.

Answer Source

Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download