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.
The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive). The substring() method does not change the original string.
To extract part string between two different characters, you can do as this: Select a cell which you will place the result, type this formula =MID(LEFT(A1,FIND(">",A1)-1),FIND("<",A1)+1,LEN(A1)), and press Enter key. Note: A1 is the text cell, > and < are the two characters you want to extract string between.
TypeScript - String substr() This method returns the characters in a string beginning at the specified location through the specified number of characters.
Try this:
test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With