Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get string between two strings with javascript [duplicate]

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.

like image 617
user3080392 Avatar asked Dec 26 '14 11:12

user3080392


People also ask

How to extract substring from string in javascript?

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.

How do you find the string between two characters?

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.

How do you get a substring from a string in TypeScript?

TypeScript - String substr() This method returns the characters in a string beginning at the specified location through the specified number of characters.


1 Answers

Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable)); 
like image 142
myTerminal Avatar answered Sep 22 '22 15:09

myTerminal