Regular expression to get a string between two strings in Javascript

Asked
Active3 hr before
Viewed126 times

5 Answers

regularexpressionstringsstring
90%

Regular expression to get a string between two strings in JavaScript,See a complete example here : How to find sub-string between two strings.,Extract substring between two string (excluding this two strings),Just use the following regular expression:

You want a regular match here, to consume the cow portion. To capture the portion in between, you use a capturing group (just put the portion of pattern you want to capture inside parenthesis):

cow(.*) milk
load more v
88%

First off, we’ll want to use the JavaScript String match method, which takes a string or regular expression as an argument.,Before we work on eliminating them, let’s evaluate what we did in our current regular expression.,The outer part / /g basically says a couple things: the forward slashes indicate that this is a regex and the g indicates that this should be a global regex (i.e., we don’t want to stop at the first match).,The new regular expression with our lookahead and lookbehind operators is as follows:

['name', 'age', 'profession'];
load more v
72%

const oldString = 'John1Doe2'

const stringBetweenCharacters = oldString.match(/1(.*?)2/i)[1] //Doe
load more v
65%

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 :,(.*?) captures all characters between cow and milk and saves it in a group. ? makes it lazy so it stops at milk.,I've tried various things including:,This matches only the middle part of the sentence.

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]);
load more v
75%

Hex To String Converter,String To Hex Converter,Binary To String Converter,String To Binary Converter

{
   {
      getLabel()
   }
}
load more v

Other "regular-expression" queries related to "Regular expression to get a string between two strings in Javascript"