クッキーサンプルスクリプト ver.2
Sample of Cookie for JavaScript

written by clone


クッキーにデータを保存する

クッキーにデータを
フィールド名=値;
の形で記録する。
function setCookie(fieldId,value){
	var expires = new Date()
	//このクッキーの賞味期限は1日です。
	expires.setTime(expires.getTime() + (1*24*60*60*1000))
	document.cookie=fieldId+"="+escape(value)+"; expires="+expires.toGMTString()
}

クッキーからフィールドの値を取得する

汎用の部品(関数)にする場合

仕様
フィールド名(文字列)を渡すとその値(文字列)を返す。
フィールドが存在しない場合 nullを返す。

昔書いたサンプルコード

枯れてるコード(正規表現無し)

function getCookie(fieldId){
	var idStr=fieldId+"="
	var startIndex=document.cookie.indexOf(idStr)
	if(startIndex>-1){
		startIndex=startIndex+idStr.length
		var endIndex=document.cookie.indexOf(";",startIndex)

		if(endIndex<0) endIndex=document.cookie.length
		return unescape(document.cookie.substring(startIndex,endIndex))
	}else{
		return null
	}
}

正規表現を使用

match()の引数を
match(new RegExp(fieldId+"=([^;]*);"))
と書いても同じ。この場合「new」がないとIE4でエラーが出ます(^^;
function getCookie(fieldId){
	var tmp=(document.cookie+";").match(fieldId+"=([^;]*);")
	if(tmp!=null){
		return unescape(tmp[1])
	}else{
		return null
	}
}
上のコードを縮めたもの。読みづらい。
function getCookie(fieldId){
	return ((document.cookie+";").match(fieldId+"=([^;]*);")!=null)? unescape(RegExp.$1):null
}
ドキュメントオブジェクトにバインドするとこんな感じ
document.getCookie=function (fieldId){
	var tmp=(this.cookie+";").match(fieldId+"=([^;]*);")
	if(tmp!=null){
		return unescape(tmp[1])
	}else{
		return null
	}
}
ついでにsetCookieも
document.setCookie=function (fieldId,value){
	var expires = new Date()
	//このクッキーの賞味期限は1日です。
	expires.setTime(expires.getTime() + (1*24*60*60*1000))
	this.cookie=fieldId+"="+escape(value)+"; expires="+expires.toGMTString()
}

関数に分離しない場合

var tmp=(document.cookie+";").match(/フィールド名=([^;]);/)
if(tmp!=null){
//フィールドが存在した場合の処理
	var value=unescape(RegExp.$1)
	//value=unescape(tmp[1])でも同じ
}else{
//フィールドが無い場合の処理
}

もどる ∧∧
(◎←)
((( ▽ )))
- -

This page hosted by Geocities-Japan
Get your own Free Home Page