0

I want to get the value stored in a cookie on my site. From "document.cookie", I get the following string :

startBAK=R3415751377; _ga=GA1.2.1180519210.1552400330; _gid=GA1.2.1693387126.1552400330; trkPV=4; ata=google.com;

I want to extract the value of ata "google.com" So I tried this :

var cookie = document.cookie;
var regex = /(?:ata=)(.*?);/g;
var value = cookie.match(regex);
return value

The result is "ata=google.com".... how can i get the value only : "google.com" ?

B4b4j1
  • 430
  • 2
  • 7
  • 24
  • 1
    try this on your third line: var value = cookie.match(regex).split("=")[1]; Edit: to explain, you need to have the ata= part in the regex, or else it can't find the match. After that, then you can get just the section you want. – Ethan Green Mar 12 '19 at 15:50
  • 2
    Use `var value = regex.exec( cookie );` Then value will be the array `["ata=google....", "google.com"]`. If a second `ata=` is found inside the string, it'll be at index 2. – Shilly Mar 12 '19 at 15:52
  • @EthanGreen It's almost that... the result is ""google.com;"... how can I remove the ";" at the end ? – B4b4j1 Mar 12 '19 at 16:43
  • 1
    @B4b4j1 best bet would be substring. I like to split it up in two lines to be easier to read. so new line would be value = value.substr(0,value.length-1); which will truncate the last character. – Ethan Green May 02 '19 at 14:13

1 Answers1

1

You can use the RegExp.prototype.exec() method:

const value = (/(?:ata=)(.*?);/g).exec(cookie)[1]
Hammerbot
  • 15,696
  • 9
  • 61
  • 103