Regular Expressionexpression to get a string between two strings in JavascriptJavaScript
The most complete solution that will work in the vast majority of cases is using a capturing group with a lazy dot matching pattern. However, a dot .
in JSJavaScript regex does not match line break characters, so, what will work in 100% cases is a [^]
or [\s\S]
/[\d\D]
/[\w\W]
constructs.
In JSJavaScript environments supporting ECMAScript 2018, s
modifier allows .
to match any char including line break chars, and the regex engine supports lookbehinds of variable length. So, you may use a regex like
This and all other scenarios below are supported by all JSJavaScript environments. See usage examples at the bottom of the answer.
###Sample regex usage in JavaScript:
//Single/First match expected: use no global modifier and access match[1]
console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]);
// Multiple matches: get multiple matches with a global modifier and
// trim the results if length of leading/trailing delimiters is known
var s = "My cow always gives milk, thier cow also gives milk";
console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);}));
//or use RegExp#exec inside a loop to collect all the Group 1 contents
var result = [], m, rx = /cow (.*?) milk/g;
while ((m=rx.exec(s)) !== null) {
result.push(m[1]);
}
console.log(result);