目的
"abc"(プリミティブ)とnew String("abc")(オブジェクト)を安全に比較したい==に頼らず、型の違いも吸収して正しく「中身」を比べる- ついでに、
nullやundefinedにも強い(落ちにくい)関数にする
シンプル版:safeStringEqual()
function safeStringEqual(a, b) {
// どちらも null または undefined の場合 → true
if (a == null && b == null) return true;
// String オブジェクトならプリミティブ値に変換
if (a instanceof String) a = a.valueOf();
if (b instanceof String) b = b.valueOf();
// どちらも文字列でなければ false
if (typeof a !== "string" || typeof b !== "string") return false;
// 中身を比較
return a === b;
}
// --- 使用例 ---
console.log(safeStringEqual("abc", new String("abc"))); // ✅ true
console.log(safeStringEqual(new String("xyz"), "xyz")); // ✅ true
console.log(safeStringEqual(new String("abc"), new String("abc"))); // ✅ true
console.log(safeStringEqual("abc", "ABC")); // ❌ false
console.log(safeStringEqual("123", 123)); // ❌ false
JavaScriptポイント解説
instanceof String
→new String()で作られたオブジェクトを検出。
その中身を.valueOf()でプリミティブに変換。typeof a !== "string"チェック
→ 予期せぬ型(数値・配列など)を安全に排除。===で最終比較
→ 型が揃ったプリミティブ文字列同士なので、厳密比較でも安全。
発展版:オプション付き(ケース無視/トリムなど)
現場では、「大文字小文字を区別しない比較」などがよく必要になります。
そのためにオプション対応版を作ります。
function safeStringEqual(a, b, options = {}) {
const { ignoreCase = false, trim = false } = options;
// nullやundefinedを安全に扱う
if (a == null && b == null) return true;
if (a == null || b == null) return false;
// Stringオブジェクトなら中身を取り出す
if (a instanceof String) a = a.valueOf();
if (b instanceof String) b = b.valueOf();
// 型チェック
if (typeof a !== "string" || typeof b !== "string") return false;
// オプション適用
if (trim) {
a = a.trim();
b = b.trim();
}
if (ignoreCase) {
a = a.toLowerCase();
b = b.toLowerCase();
}
return a === b;
}
// --- 使用例 ---
console.log(safeStringEqual(" Hello ", new String("hello"), { ignoreCase: true, trim: true })); // ✅ true
console.log(safeStringEqual("abc", "ABC", { ignoreCase: true })); // ✅ true
console.log(safeStringEqual("abc", "ABC")); // ❌ false
console.log(safeStringEqual("abc", 123)); // ❌ false
JavaScriptおまけ:型を確認したいときのヘルパー
function getStringType(value) {
if (typeof value === "string") return "primitive";
if (value instanceof String) return "object";
return typeof value;
}
console.log(getStringType("abc")); // "primitive"
console.log(getStringType(new String("abc"))); // "object"
console.log(getStringType(123)); // "number"
JavaScriptまとめ
| 機能 | 説明 |
|---|---|
safeStringEqual() | プリミティブ/オブジェクト混在でも安全比較 |
ignoreCase オプション | 大文字小文字を無視できる |
trim オプション | 前後の空白を無視できる |
getStringType() | 文字列の種類(プリミティブ/オブジェクト)を調べる |

