phil phil - 1 month ago 7
Javascript Question

Regular Expression to get a string between two strings in Javascript

I have found very similar posts but I can't quite get my regular expression right here.

I am trying to write a regular expression which returns a string which is between two other strings. For example: I want to get the string which resides between the strings "cow" and "milk"


My cow always gives milk


would return


"always gives"


Here is the expression I have pieced together so far:

(?=cow).*(?=milk)


However this returns the string "cow always gives"

Solution



I was able to get what I needed using Martinho Fernandes' solution below. The exact code is:

var test = "My cow always gives milk";

var testRE = test.match("cow(.*)milk");
alert(testRE[1]);


You'll notice that I am alerting the testRE variable as an array. This is because testRE is returning as an array, for some reason. The output from:


My cow always gives milk


Changes into:


always gives

Answer

A lookahead (that (?= part) does not consume any input. It is a zero-width assertion (as are boundary checks and lookbehinds).

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

No lookaheads are needed at all.