1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascriptでcookieを扱う

Last updated at Posted at 2018-10-30

Javascriptでcookieを扱う

案件でCookieを扱う機会があったので、基本的なとこと重複チェックの方法をメモをしておきます。

// 書き込み
document.cookie = 'name1=value1';
document.cookie = 'name2=value2';

// ,;スペースは使えない。使いたい場合は、encodeURIComponent()関数でエンコードする。


// pathとsecureの指定を忘れずに
document.cookie = 'name=value;path=/;secure';


// 取得
var allCookie = document.cookie;
console.log(allCookie); // "name1=value1; name2=value2"


// 削除
document.cookie = 'name=value;max-age=0';

##重複チェック

// indexOfを使う
var allCookie = document.cookie;
var check = allCookie.indexOf('確認したい値');
console.log(check); // -1が返ってきたら重複無し

// 大文字、小文字は区別する(Appleとappleは別物)
// 重複があった場合は、その文字列が現れる最初の番号を返す。0から
// 第2引数に、呼び出す文字列内の検索を始めるための位置を指定できる。デフォルトは0
/*
"Blue Whale".indexOf("Blue");     // 0
"Blue Whale".indexOf("Blute");    // -1
"Blue Whale".indexOf("Whale", 0); // 5
"Blue Whale".indexOf("W", 0);     // 5
*/


// split()を2回使う
var allCookie = document.cookie;
var tmp = allCookie.split('; '); // [name=value,name2=value2...]という配列が作る
var flg = true;
for (var i = 0; i < tmp.length; i++) { // [name,value][name2,value2]...という配列を作る
	var data = tmp[i].split('='); 
	if (decodeURIComponent(data[1]) == '確認したい値') {
		flg = false;
	}
}
console.log(flg); // trueなら重複無し

単純にチェックだけなら、indexOf、上書きとかしたいならsplitの方を使うと便利かなと思いました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?