0
0

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 3 years have passed since last update.

JavaScript: Cookieから特定要素を見つけ出す際のトリム

0
Posted at

jQuery.Cookieなどのラッピングされたものを使用する場合には、なんの考慮もいらないはずです。
裸のJavaScriptでハンドリングする場合に忘れがちなのがトリムです。

サンプル

function getCookie (key) {
  var cookies = document.cookie;
  var cookiesArray = cookies.split(';');
  for (var tuple of cookiesArray){
    var strArray = tuple.split('=');
    var str = strArray[0];
    if (str.trim() == key) {  // トリムしてあげましょう
      str = strArray[1];
      return str.trim();
    }
  }
  return '';
}

CやPerlなんかで書く場合には、まあ忘れることはないんですけどね。私の場合、JavaScriptの場合が特に油断しますね。
トリムのオーバーヘッドなんてわずかでしょうからね、私の場合は、要らないんじゃない?と思える場合でもとりあえずトリムしますよ。

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?