1

I have this string

"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"

And i need some sort of function to split this string given an argument , for example given that my string is text

text.split(";") , will split it into an array separating it by ";"

But i need a function like this

returnText(text , property) that would work like

returnText(text, "_gcl_au") --> returns "someglcau"
Aalexander
  • 4,987
  • 3
  • 11
  • 34
mouchin777
  • 1,428
  • 1
  • 31
  • 59
  • 1
    Also have a look at [this](https://stackoverflow.com/questions/10730362/get-cookie-by-name). Just replace `document.cookie` in the answers to them with `text` for your case. – Remi Guan Dec 15 '20 at 08:34

2 Answers2

2

You could actually use a regex replacement approach here, for a one-liner option:

function returnText(text, property) {
    var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
    return term;
}

var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

you can use split, just as you tried:

function returnText(text , property){
    entries = text.split('; ');
    const newEntries = [];
    entries.forEach(item => {
       let vals = item.split('=');
       newEntries[vals[0]] = vals[1]
    });
    return newEntries[property];
}
    
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));
vlad katz
  • 534
  • 3
  • 9