0

How do I get content inside two strings?

Example:

Main string:

document.cookie="cookie=name";

How do I select the cookie=name part?

I tried this:

document.cookie=\"(.*?)\";

But this select the hole string not the cookie=name.

  • Your regex seems to do fine. You just need to [extract the first group from it](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression). – Ivar Dec 15 '18 at 23:50
  • https://stackoverflow.com/questions/1352128/whats-the-regex-to-match-anything-except-a-double-quote-not-preceded-by-a-backs – J-Cake Dec 15 '18 at 23:57
  • `"\"cookie=name\"".match(/\"(.*?)\"/)[1]` – J-Cake Dec 16 '18 at 00:06
  • Possible duplicate of [How do you access the matched groups in a JavaScript regular expression?](https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression) – The fourth bird Dec 16 '18 at 09:18

3 Answers3

2

You can use split:

str.split('"')[1]
trincot
  • 317,000
  • 35
  • 244
  • 286
1

You have it, just extract the first match

var regex = /document.cookie=\"(.*?)\";/;
var match = regex.exec('document.cookie="cookie=name";');
console.log(match[1]);
Damo
  • 5,698
  • 3
  • 37
  • 55
0

let str = 'document.cookie="cookie=name"';
let regx = /\".+=.+\"$/;

let match = str.match(regx)[0].replace(/\"/g, "");
console.log(match);

let [data, name] = match.split("=");
console.log("Data: " + data + " and name: " + name);

While splitting the string on a double quote is certainly efficient, the OP composed the post in a way that expresses interest in using a regex, a point this answer addresses. You may isolate the portion you wish to extract from the outer string with a regex that matches a pattern located at the end of str. Next, the string uses its replace method to globally replace all its double quotes. Then, the overall result is assigned to variable match, At this point, one now has extracted the inner string 'cookie=name'.

Of course, you may manipulate match by splitting its string value on the equals character as this code does in a statement that employs array destructuring. This action results in variables data and name respectively containing the values "cookie" and "name".

slevy1
  • 3,797
  • 2
  • 27
  • 33