Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  145] [ 1]  / answers: 1 / hits: 81169  / 10 Years ago, fri, december 26, 2014, 12:00:00

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.


More From » regex

 Answers
115

Try this:



test.match(new RegExp(firstvariable + (.*) + secondvariable));

[#68378] Tuesday, December 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;