The easiest way to get cookies in JS

const getCookie = (name) => document.cookie.match(`[;\s+]?${name}=([^;]*)`)?.pop();

// For example, the cookie is as follows: a=b; c=d

// use

getCookie(‘c’) // d

where match is the prototype method for strings.

str.match(regexp)

If a non-regex object is passed in, it is implicitly converted to a RegExp using new RegExp(obj)

The above, so there is no need to write a regular, because the regular spelling string also uses the new RegExp construction method, but the match is internal. It has been implicitly judged.

The implementation principle of the search method on the string prototype is the same, because the latter refers to the return index, similar to indexOf, so the performance will be better.

A bit off topic, might as well run further. . .

In fact, the match method on string actually calls the regular prototype RegExp[Symbol.match] method.

const str = ‘foo’;

str.match(/foo/); // [‘foo’]

RegExp.prototype[Symbol.match].call(/foo/, str); //[‘foo’]

The post The easiest way to get cookies in JS first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9882
This site is for inclusion only, and the copyright belongs to the original author.