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.

Answer from R. Martinho Fernandes on Stack Overflow
Top answer
1 of 12
250

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.

2 of 12
148

Regular expression to get a string between two strings in JavaScript

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 JavaScript regex does not match line break characters, so, what will work in 100% cases is a [^] or [\s\S]/[\d\D]/[\w\W] constructs.

ECMAScript 2018 and newer compatible solution

In JavaScript 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

var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any
// Or
var result = s.match(/(?<=cow\s*).*?(?=\s*milk)/gs); // Same but whitespaces are optional

In both cases, the current position is checked for cow with any 1/0 or more whitespaces after cow, then any 0+ chars as few as possible are matched and consumed (=added to the match value), and then milk is checked for (with any 1/0 or more whitespaces before this substring).

Scenario 1: Single-line input

This and all other scenarios below are supported by all JavaScript environments. See usage examples at the bottom of the answer.

cow (.*?) milk

cow is found first, then a space, then any 0+ chars other than line break chars, as few as possible as *? is a lazy quantifier, are captured into Group 1 and then a space with milk must follow (and those are matched and consumed, too).

Scenario 2: Multiline input

cow ([\s\S]*?) milk

Here, cow and a space are matched first, then any 0+ chars as few as possible are matched and captured into Group 1, and then a space with milk are matched.

Scenario 3: Overlapping matches

If you have a string like >>>15 text>>>67 text2>>> and you need to get 2 matches in-between >>>+number+whitespace and >>>, you can't use />>>\d+\s(.*?)>>>/g as this will only find 1 match due to the fact the >>> before 67 is already consumed upon finding the first match. You may use a positive lookahead to check for the text presence without actually "gobbling" it (i.e. appending to the match):

/>>>\d+\s(.*?)(?=>>>)/g

See the online regex demo yielding text1 and text2 as Group 1 contents found.

Also see How to get all possible overlapping matches for a string.

Performance considerations

Lazy dot matching pattern (.*?) inside regex patterns may slow down script execution if very long input is given. In many cases, unroll-the-loop technique helps to a greater extent. Trying to grab all between cow and milk from "Their\ncow\ngives\nmore\nmilk", we see that we just need to match all lines that do not start with milk, thus, instead of cow\n([\s\S]*?)\nmilk we can use:

/cow\n(.*(?:\n(?!milk$).*)*)\nmilk/gm

See the regex demo (if there can be \r\n, use /cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm). With this small test string, the performance gain is negligible, but with very large text, you will feel the difference (especially if the lines are long and line breaks are not very numerous).

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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Using the modern String#matchAll method

const s = "My cow always gives milk, thier cow also gives milk";
const matches = s.matchAll(/cow (.*?) milk/g);
console.log(Array.from(matches, x => x[1]));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
TypeOfNaN
typeofnan.dev › how-to-capture-between-two-characters-in-javascript-using-regex
How to Capture Between Two Characters in JavaScript using Regular Expressions | TypeOfNaN
January 1, 2021 - Today we’ll use regex to capture all content between two characters. ... First off, we’ll want to use the JavaScript String match method, which takes a string or regular expression as an argument. const str = 'Hi there, my name is [name], I am [age] years old, and I work in the field of [profession].'; const matches = str.match(/some regex here/); We want to capture between the brackets. Our first go at this might include a regex that looks like this: /\[.+?\]/g. If we use this, we get the following:
Discussions

regex - Get Substring between two characters using JavaScript - Stack Overflow
I am trying to extract a string from within a larger string where it get everything in between a : and a ; Current Str = 'MyLongString:StringIWant;' Desired Output newStr = 'StringIWant' More on stackoverflow.com
🌐 stackoverflow.com
December 17, 2014
javascript - Regex get all content between two characters - Stack Overflow
I need to get content between symbols [ and ] even there are other same characters i need to take content between first [ and last ]. In jquery useing regex. Thanks Advance More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
javascript - Regex to get the text between two characters? - Stack Overflow
I want to replace a text after a forward slash and before a end parantheses excluding the characters. My text: notThisText/IWantToReplaceThis) $('h3').text($('h3').text().rep More on stackoverflow.com
🌐 stackoverflow.com
January 31, 2017
How do I match a string between characters in javascript regex - Stack Overflow
I'm trying to match just the characters between some set characters using regex? I'm very new to this but I'm getting somewhere... I want to match all instances of text between '[[' and ']]' in the More on stackoverflow.com
🌐 stackoverflow.com
May 6, 2017
Top answer
1 of 2
58

Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));
2 of 2
14

Use this code

const regExString = new RegExp(`(?<=${firstVariable}).*?(?=${secondVariable})`, "ig"); //set ig flag for global search and case insensitive

const testRE = regExString.exec("My cow always gives milk.");
if (testRE && testRE.length > 0) //RegEx has found something and has at least one entry.
{  
    alert(testRE[0]); //is the matched group if found
}

This matches only the middle part of the sentence.

  1. (?<="+firstvariable+") finds but does not capture cow :: lookbehind is possible now.
  2. .*? captures all characters between cow and milk and saves it in a group. ? makes it lazy so it stops at milk.
  3. (?="+secondvariable+") finds but does not capture milk. :: lookahead

You can test this below:

const test = document.getElementById("testStringDiv").textContent;
let firstVariable = "";
let secondVariable = "";
function testString()
{
    firstVariable = document.querySelectorAll("input")[0].value; //first input;
    secondVariable = document.querySelectorAll("input")[1].value; //second input;
    
    //build the regex:
    //lookbehind is possible in JavaScript now: (?<=) sees if the content in the matched group is preceded by the first       variable, but does not capture this.
    //for the second variable we use the (?=) which is a lookahead and does the same as the lookbehind.
    //If there is a match, the string returned will be the one in the captured group (.*?)
    let regExString = new RegExp(`(?<=${firstVariable}).*?(?=${secondVariable})`, "ig");
    const testRE = regExString.exec(test);

    if (testRE && testRE.length > 0)
    {  
      document.getElementById("showcase").textContent = testRE[0]; //return second result.
    }
}
document.getElementById("test").addEventListener("click", testString, true);
<div id="testStringDiv">My cow always gives milk</div>
<div id="showcase">Result will display here...</div>
<input placeholder="enter first var"/><input placeholder="enter second var"/><button id="test">Search in between...</button>

🌐
CodePen
codepen.io › seansean › pen › QxjqVp
RegEx Find String Between Two Strings
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-substring-between-two-characters
Get a Substring between 2 Characters in JavaScript | bobbyhadz
Get a Substring between 2 Characters ... using regex · To get a substring between two characters: Get the index after the first occurrence of the character....
🌐
Regex Tester
regextester.com › 96872
Extract String Between Two STRINGS - Regex Tester/Debugger
Regex Tester is a tool to learn, build, & test Regular Expressions (RegEx / RegExp). Results update in real-time as you type. Roll over a match or expression for details. Save & share expressions with others. Explore the Library for help & examples. Undo & Redo with {{getCtrlKey()}}-Z / Y. Search for & rate Community patterns. ... extended (x) extra (X) single line (s) unicode (u) Ungreedy (U) Anchored (A) dup subpattern names(J) ... Url checker with or without http:// or https:// Match string not containing string Check if a string only contains numbers Only letters and numbers Match elements
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 41955894 › regex-to-get-the-text-between-two-characters
javascript - Regex to get the text between two characters? - Stack Overflow
January 31, 2017 - I want to replace a text after a forward slash and before a end parantheses excluding the characters. My text: notThisText/IWantToReplaceThis) $('h3').text($('h3').text().rep
🌐
RegExr
regexr.com › 38prd
string between two strings
RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp). Supports JavaScript & PHP/PCRE RegEx.
🌐
RegExr
regexr.com › 397dr
RegExr: Select all characters between
RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp). Supports JavaScript & PHP/PCRE RegEx.
Top answer
1 of 2
5

URLSearchParams would make things significantly easier:

const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';
const query2 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue&someMoreParam=dummy_value2';

const params1 = new URLSearchParams(query1);
const params2 = new URLSearchParams(query2);

console.log(`For Query1: result = ${params1.get('requiredParam')}`);
console.log(`For Query2: result = ${params2.get('requiredParam')}`);

It's supported natively in the vast majority of browsers, but not all. For the rest, here's a polyfill. It's better not to re-invent the wheel when you don't need to, and it's good when you're able to use a standard API (with examples and documentation and Stack Overflow answers about it, etc).

As a side note - when using regular expressions, I'd recommend using capture groups only when necessary. If all you need to do is group some tokens together logically (like for a | alternation), non-capturing groups should be preferred. That is, if URLSearchParams didn't exist, better to do (?:&|$) than (&|$). Reserve capturing groups for when you need to save and use the captured result somewhere - otherwise, non-capturing groups are more appropriate, less expensive, and require less cognitive overhead.

If you had to go the regex route, another slight improvement would be to use a negative character class instead of lazy repetition. In the pattern, you have:

(.*?)(&|$)

Lazy repetition is slow; it forces the engine to advance one character at a time, then check the rest of the pattern for a match, and repeat until the match is found. Since you know that the capture group will not contain any &s, better to match anything but &s:

([^&]*)

Once you do that, you don't even need the final (&|$) or (?:&|$) due to the greedy repetition.

2 of 2
1

Bug with variable declarations

The keywords const and let are only supported (partially) by IE 111 2.

I don't have IE 9 but I do have IE 11 and set the Document mode to IE 9.

Running the first line in a sandbox on jsBin.com :

const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';

led to an error in the console:

In order to properly support IE 9 users, use var instead of const and let.

🌐
Bubble
forum.bubble.io › need help
Using Regex to extract a string between two strings - Need help - Bubble Forum
December 19, 2022 - I am trying to use the extract with Regex function to extract a string that is always sitting between two strings of texts that never change. Here are 3 examples I want {“key”:“1671291382053x721052777787162600”} to return 1671291382053x721052777787162600 I want {“key”:“1671128263833x743710543152935700”} to return 1671128263833x743710543152935700 I want {“key”:“1671128291585x470773579005820900”} to return 1671128291585x470773579005820900 When using this regex pattern {“key”:“(.*)”} with this...
🌐
GitHub
gist.github.com › vxhviet › 6533c0be8ccc310edb4b10d90d0d383b
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · GitHub
Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Raw · regex.md · Source: StackOverflow · Question: Regular Expression to find a string included between two characters while EXCLUDING the delimiters · Answer: Easy done: (?<=\[)(.*?)(?=\]) Technically that's using lookaheads and look behinds.
🌐
Snowflake Community
community.snowflake.com › s › article › How-to-fetch-a-string-between-2-slashes-using-regular-expressions
How to fetch a string between 2 characters using regular expressions
Explanation: The above expression is looking for slash (/) and then captures all the non-slash characters (^) and ends before the next slash(/).
🌐
Java2Blog
java2blog.com › home › javascript › get string between two characters in javascript
Get String Between Two Characters in JavaScript [4 Ways] - Java2Blog
January 27, 2023 - Use the substring() method to extract a substring that is between two specific characters from the given string in JavaScript.
🌐
Stack Overflow
stackoverflow.com › questions › 74060541 › how-can-i-get-all-the-string-between-two-characters-using-regex
javascript - How can I get all the string between two characters using regex? - Stack Overflow
I would like to get whatever is between "{" and "}". I am using this Regex /(?<=<)(.*?)(?=>)/, but is only gives me back the first one and I want to get all of them.