Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Last active November 1, 2021 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeDDHH/7b830f7253204771e5cbc81ea0d023a0 to your computer and use it in GitHub Desktop.
Save LeeDDHH/7b830f7253204771e5cbc81ea0d023a0 to your computer and use it in GitHub Desktop.
javascriptで使えそうなワンライナー

ブラウザのCookieの値を取得

  • document.cookie でアクセスしてCookieの値を取得する
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();

cookie('_ga');
// Result: "GA1.2.1929736587.1601974046"

RGB値をHex値に変換する

const rgbToHex = (r, g, b) =>
  "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 51, 255); 
// Result: #0033ff

クリップボードにコピーする

  • navigator.clipboard.writeText を使って、テキストをコピーする
const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("Hello World");

有効な日付なのかをチェックする

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

isDateValid("December 17, 1995 03:24:00");
// Result: true

1年中、何日目なのかを出力する

const dayOfYear = (date) =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());
// Result: 272

英語の文字列の最初の文字を大文字にする

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// Result: Follow for more

指定した2つの日付間の日数を出力する

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2020-10-21"), new Date("2021-10-22"))
// Result: 366

Cookieをすべて削除する

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

ランダムなHex値を生成する

  • Math.randompadEnd を使って、ランダムな16進数を生成する
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;

console.log(randomHex());
// Result: #92b008

配列から重複する値を排除する

  • Set を使うと簡単にできる
const removeDuplicates = (arr) => [...new Set(arr)];

console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
// Result: [ 1, 2, 3, 4, 5, 6 ]

URLからクエリパラメータを取得する

  • window.location または生のURLを渡すことで、URLからクエリパラメータを取得する
const getParameters = (URL) => {
  URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}');
  return JSON.stringify(URL);
};

getParameters(window.location)
// Result: { search : "easy", page : 3 }

指定した日付からのログ用の時間を出力する

  • 指定した日付から 時間:分:秒 の形式で時間を出力する
const timeFromDate = date => date.toTimeString().slice(0, 8);

console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"

数値が偶数か奇数かを確認する

const isEven = num => num % 2 === 0;

console.log(isEven(2)); 
// Result: True

指定した数値の平均を出力する

  • reduce を使って複数の数値の平均を出力する
const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);
// Result: 2.5

トップまでスクロールさせる

  • window.scrollTo を使う
  • x、yを0に指定する
const goToTop = () => window.scrollTo(0, 0);

goToTop();

文字列を逆順にする

  • split, reverse , join を使う
const reverse = str => str.split('').reverse().join('');

reverse('hello world');     
// Result: 'dlrow olleh'

配列の空チェック

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]);
// Result: true

現在選択しているテキストを取得する

  • getSelection をつかって、ユーザーが現在選択しているテキストを取得する
const getSelectedText = () => window.getSelection().toString();

getSelectedText();

配列をシャッフルする

  • sort, random を使う
const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]

ダークモードを判定する

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode) // Result: True or False

文字列の"ture"、"false"をBoolean型に変換する

const stringTrue = "true"
const stringFalse = "false"

const BooleanString = (string) => JSON.parse(string.toLowerCase())

console.log(BooleanString(stringTrue)) // Result: true
console.log(BooleanString(stringFalse)) // Result: false

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment