Doug Fir Doug Fir - 1 month ago 6
Javascript Question

regex for this cookie value?

I have a cookie with a long value, I have pasted an example below. I need to split on name value pairs and return, in this case "id" which from below corresponds to

167814329
.

I'm having trouble reading what syntax the developers have used here (I'm a analyst not dev engineer). In the past I have seen name value pairs used with = or '|' syntax as a separator.

It looks like the name value pair is like so:

%22id%22%3A167814329%2C

var usd = document.cookie.match(/(^| )user_session_data\=([^;]*)(;|$)/)[0]
var arr = usd.split('%22')
var ind = arr.indexOf('id');
var pair = arr[ind];


But pair is equal to "id" only, I was hoping to get this array value
%22id%22%3A167814329%2C
which I could then split.

What would be a clean regex to get 167814329?

Here is the example cookie value to search through:

user_session_data=%7B%22lastUpdated%22%3A1476155189.373%2C%22active%22%3Afalse%2C%22uType%22%3A%22none%22%2C%22entitled%22%3Afalse%2C%22gift%22%3Afalse%2C%22stacked%22%3A%22none%22%2C%22usedsomestringFreeTrial%22%3A%22none%22%2C%22cancelled%22%3A%22none%22%2C%22displayName%22%3A%2220161010_gpc%40example.com%22%2C%22email%22%3A%2220161010_gpc%40example.com%22%2C%22userName%22%3A%2220161010_gpc%40example.com%22%2C%22firstName%22%3Anull%2C%22salesChannel%22%3A%22cat%22%2C%22marketingOptIn%22%3Atrue%2C%22newIssueEmailNotifyEnabled%22%3Afalse%2C%22restartSubscriptions%22%3A%5B%5D%2C%22id%22%3A167814329%2C%22purchaseType%22%3A%22NONE%22%2C%22futurePurchaseType%22%3A%22NONE%22%2C%22somestringStatus%22%3Anull%2C%22hasFuturePrivilege%22%3Afalse%2C%22rogersUser%22%3Afalse%2C%22suspendedStatus%22%3Anull%2C%22socialEmail%22%3A%22%22%2C%22somestringOffersStale%22%3Anull%2C%22somestringcabbagesPrice%22%3Anull%2C%22somestringcabbagesId%22%3Anull%2C%22somestringcabbagesFreeTrial%22%3Anull%2C%22somestringcabbagesOfferPackageId%22%3Anull%2C%22somestringcarrotsPrice%22%3Anull%2C%22somestringcarrotsId%22%3Anull%2C%22somestringcarrotsFreeTrial%22%3Anull%2C%22somestringcarrotsOfferPackageId%22%3Anull%2C%22launchedFromReader%22%3Anull%2C%22userPaymentMethod%22%3Anull%2C%22iseligibleforfreetrial%22%3Atrue%2C%22loginTimeStamp%22%3A%22Tue%20Oct%2011%202016%2011%3A06%3A29%20GMT%2B0800%20(PHT)%22%2C%22latestSubscriptionSource%22%3Anull%7D;"

Answer

Hanlet Escaño definitely has the most accurate answer, but if you really wanted to use regex you can. It was unclear whether you wanted id%22%3a[ID]%2C or just the ID, so here's both:

Full string: (?:^| )user_session_data\=[^;]*(id%22%3A\d+%2C)[^;]*(?:;|$)

Just the ID: (?:^| )user_session_data\=[^;]*id%22%3A(\d+)%2C[^;]*(?:;|$)

In the future, if you're having trouble with a regex, this site can be extremely useful.

Comments