🌻

JavaScriptの文字列,数値,日付操作まとめメモ

2024/06/28に公開


思い出し用メモ2です。標準の日付の操作はしっかり確認したのが初めてだったので癖がありすぎてウーン感がすごかったです。

文字列

普通の操作

// merge strings   (each method almost same performance on https://jsbench.me/)
str = str1 + str2;                   // clear for up to 2 strings
str = str1.concat(str2, str3, ...);  // 3 or more concatenate
str = `${str1}${str2}${str3}`;       // complex concatenate
// str = [str1, str2, str3].join(""); is too slow

// count char
num = str.length;       // if definitely be only ascii chars
num = [...str].length;  // incorrect if str includes some of emoji like "🏴󠁧󠁢󠁥󠁮󠁧󠁿"
num = [...(new Intl.Segmenter("ja", { granularity: "grapheme" }).segment(str))].length;  // flawless

// cast to string
str = num.toString();
str = ary.join(",");
str = JSON.stringify(obj);
str2 = encodeURI(str);
str2 = decodeURI(str);

// cast from string
num = Number.parseFloat(str);  // "a"->NaN ""->NaN null->NaN undefined->NaN
num = Number(str);             // "a"->NaN ""->0   null->0   undefined->NaN
bint = BigInt(str);            // "a"->Err ""->0n  null->Err undefined->Err
ary = str.split(",");
obj = JSON.parse(str);

// check existence
bool = str.startsWith(foo);  // regex is not supported
bool = str.endsWith(foo);    // regex is not supported
bool = str.includes(foo);    // regex is not supported

// get index of the value
num = str.indexOf(foo);  // return -1 if not found; case-sensitive

// replace partially
str2 = str.replace(foo, bar);     // replace foo to bar once
str2 = str.replaceAll(foo, bar);  // replace all foo to bar
str2 = str.replaceAll(foo, x => x.toUpperCase()); // replace all foo to upper case

// get partial string (i < j)
str2 = str.slice(i);     // "abcde" -> "cde"
str2 = str.slice(i, j);  // "abcde" -> "bcd"
str2 = str.slice(0, j);  // "abcde" -> "abc"
str2 = str.substring(j, i);  // work like substring(i, j)

// align
str2 = str.toUpperCase();
str2 = str.toLowerCase();

文字列結合の速度比較

img_performance_concat

正規表現の操作

// check existence
bool = /regex/.test(str);

// get first matching index
num = str.search(/regex/);        // return -1 if not found
num = str.match(/regex/)?.at(1);  // return undefined if not found

// get first matching string
str = str.match(/regex/)?.shift();  // return undefined if not found

// replace matching string
str = str.replace(/regex/, foo);   // replace first one
str = str.replace(/regex/g, foo);  // replace all

// get all matching string
ary = str.match(/regex/g);      // as array; return null if not found
iter = str.matchAll(/regex/g);  // as iterable; required g sign

// get capture group with name
// const matches = "2000-01-02".match(/(?<year>\d+)-(?<month>\d+)-(?<date>\d+)/);
// matches.groups.year  -> "2000"
// matches.groups.month -> "01"
// matches.groups.date  -> "02"

数値

// control flow that y is 0 or not
bool = Number.isFinite(x / y);  // 1/0 -> Infinity, -1/0 -> -Infinity, 0/0 -> NaN
// cast from str is failed or not, etc.
bool = Number.isNaN(num);
// confirm integer or not
bool = Number.isInteger(num);

// rounding (to integer)
num = Math.round(num);
num = Math.ceil(num);
num = Math.floor(num);
// extract integer part
num = Math.trunc(num);

// get maximum,minimum among args
num = Math.max(num1, num2, ...);
num = Math.min(num1, num2, ...);

// get absolute value and sign
num = Math.abs(num);
num = Math.sign(num);

// get random number
num = Math.random();  // 0 <= num < 1; not secure

丸め方と結果リスト

メソッド -7.5 -7.4 -6.5 -6.4 6.4 6.5 7.4 7.5
Math.round -7 -7 -6 -6 6 7 7 8
Math.ceil -7 -7 -6 -6 7 7 8 8
Math.floor -8 -8 -7 -7 6 6 7 7
Math.trunc -7 -7 -6 -6 6 6 7 7

日付

  • Dateは内部的にUTCとして管理されている
  • コンストラクターの月指定は0-11で表現する
// cast to datetime
dt = new Date(Date.now());    // now
dt = new Date("2000-01");     // specify month as UTC
dt = new Date("2000-01-01");  // specify date as UTC
dt = new Date(2000, 0, 1);    // specify date as local timezone
dt = new Date("2000-01-01T00:00:00Z");       // specify datetime as UTC
dt = new Date(2000, 0, 1, 0, 0, 0);          // specify datetime as local timezone
dt = new Date("2000-01-01T00:00:00+09:00");  // specify datetime as JST
dt = JSON.parse(str);

// cast from datetime
str = dt.toISOString();    // datetime as UTC "2000-01-01T00:00:00.000Z"
str = JSON.stringify(dt);  // datetime as UTC "2000-01-01T00:00:00.000Z"
str = dt.toLocaleString("lt", {timeZone: "Asia/Tokyo"});  // datetime as JST "2000-01-01 09:00:00" hmm...
str = dt.toISOString().slice(0, 10);                          // date as UTC "2000-01-01"
str = dt.toLocaleDateString("lt", {timeZone: "Asia/Tokyo"});  // date as JST "2000-01-01" hmm...

// get partial datetime as local timezone
num = dt.getFullYear();  // year
num = dt.getMonth()+1;   // month
num = dt.getDate();      // date
num = dt.getHours();     // hour
num = dt.getMinutes();   // minute
num = dt.getSeconds();   // second

// get partial datetime as UTC
num = dt.getUTCFullYear();  // year
num = dt.getUTCMonth()+1;   // month
num = dt.getUTCDate();      // date
num = dt.getUTCHours();     // hour
num = dt.getUTCMinutes();   // minute
num = dt.getUTCSeconds();   // second

// compare 2 datetimes
bool = dt1.getTime() === dt2.getTime();

// adjust date (automatically move up/down to month,year)
dt.setDate(dt.getDate() + num);  // add destructive
dt.setDate(-num);  // sub destructive

参考文献

Discussion