var cookie = 'intercom-id-mrtzdw2q=c2be8491-1730-4343-b16e-1c708643318e; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiIsImtpZCI6IjhjMTgyMTY1YWNmN2U3Yjg3NzkwNzcxNWFmZWRiNzhmIn0.e30.McvbBVzvGzsawYch7ToCgtCrUicIQZ3_wNBV93fVBMm90JTldSpzdDgXd0eY7au1AxQst08mH-7FVy4C8wr4EQ; intercom-session=acj; intercom-session-mq='
const TOKEN_REGEXP = /token=(\S+)/
const [, token] = TOKEN_REGEXP.exec(cookie)
console.log(token)
const token = cookie?.split('token=')[1]
? cookie.split('token=')[1].split(';')[0]
: undefined
console.log(token)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Regexp | |
Split |
Test name | Executions per second |
---|---|
Regexp | 202318.1 Ops/sec |
Split | 192081.7 Ops/sec |
The test on MeasureThat.net is designed to compare the performance of two approaches for extracting a token from a cookie string in JavaScript: using regular expressions (Regexp) versus splitting the string.
Options compared:
exec()
and destructuring it into an array (const [, token] = TOKEN_REGEXP.exec(cookie)
).[1]
.split(';')[0]
).Pros and Cons of each approach:
Regexp:
Pros:
Cons:
Split method:
Pros:
Cons:
Other considerations:
cookie
string contains additional data (e.g., intercom-session and intercom-session-mq) that may affect performance. The benchmark assumes that these parts are not relevant for extracting the token.Token_REGEXP
pattern in Regexp test uses a raw string literal (/token=(\\S+)/
) to avoid issues with backslashes and escape sequences.Library usage:
None of the code snippets use any external libraries or frameworks beyond JavaScript's built-in functionality.
Special JS feature or syntax:
The Regexp test uses an arrow function syntax (e.g., const [, token] = TOKEN_REGEXP.exec(cookie)
) to simplify the execution. This is a modern JavaScript feature introduced in ECMAScript 2015 (ES6).