JavaScript | Stringオブジェクト

JavaScript JavaScript
スポンサーリンク

自動検出ツール(lintスクリプト) – コード中の new String() を自動検出して警告

実際のチーム開発やレビューで「new String()をうっかり使ってしまう」バグを自動検出できるようにするのはとても有効です。

ここでは、
軽量なESLintルール風スクリプト(自作チェックツール)
Node.jsで単体でも動かせるサンプルコード
の両方を示します。

目的

JavaScriptファイル中の new String(...) の使用を検出して警告を出す。


方法1:Node.js 単体スクリプト(正規表現で検出)

シンプルな検出スクリプトです。
scan-string-object.js というファイルに保存して、
node scan-string-object.js yourfile.js
でチェックできます。

// scan-string-object.js
// ----------------------------------------
// JavaScript ファイル中に new String() が使われていないか検出するツール
// 使い方: node scan-string-object.js target.js
// ----------------------------------------

import fs from "fs";
import path from "path";

// コマンドライン引数からファイルパス取得
const file = process.argv[2];
if (!file) {
  console.error("❌ チェック対象ファイルを指定してください。");
  process.exit(1);
}

const source = fs.readFileSync(file, "utf8");

// new String(...) のパターンを検索
const regex = /\bnew\s+String\s*\([^)]*\)/g;
let match;
let hasWarning = false;

while ((match = regex.exec(source)) !== null) {
  const line = source.slice(0, match.index).split("\n").length;
  console.warn(`⚠️  [警告] new String() が検出されました: 行 ${line}`);
  hasWarning = true;
}

if (!hasWarning) {
  console.log("✅ new String() の使用は検出されませんでした。");
} else {
  console.log("\n💡 修正ヒント: new String() の代わりに String() または文字列リテラルを使用してください。");
}
JavaScript

実行例

$ node scan-string-object.js test.js
⚠️  [警告] new String() が検出されました: 行 12

💡 修正ヒント: new String() の代わりに String() または文字列リテラルを使用してください。
Bash

方法2:ESLintカスタムルールとして組み込む

もしESLintを使っているなら、
プロジェクトに次のようなカスタムルールを追加できます。

no-new-string.js

// ESLint Custom Rule: no-new-string
export default {
  meta: {
    type: "problem",
    docs: {
      description: "Disallow use of new String() (use String() or literals instead)",
      category: "Possible Errors",
    },
    messages: {
      avoidNewString: "Avoid using 'new String()'. Use 'String()' or string literals instead.",
    },
  },
  create(context) {
    return {
      NewExpression(node) {
        if (node.callee.name === "String") {
          context.report({
            node,
            messageId: "avoidNewString",
          });
        }
      },
    };
  },
};
JavaScript

eslint.config.js に追加

import noNewString from "./no-new-string.js";

export default [
  {
    files: ["**/*.js"],
    rules: {
      "no-new-string/avoid-new-string": "error",
    },
    plugins: {
      "no-new-string": { rules: { "avoid-new-string": noNewString } },
    },
  },
];
JavaScript

実行例

$ npx eslint test.js
test.js
  5:10  error  Avoid using 'new String()'. Use 'String()' or string literals instead.  no-new-string/avoid-new-string
Bash

コードレビュー視点での補足

このような静的チェックは次のバグを防ぎます:

検出パターン防げるバグ例
new String("...")比較で false になる (===)
new String("")truthy になる誤判定
JSON.stringify で {} になるデータ化バグ
Mapキーが分離ロジックずれ

拡張例(検出+自動修正提案)

ESLintの「fix」機能を使えば、new String(...) を自動的に String(...) に直すことも可能:

// 修正版 no-new-string.js
export default {
  meta: {
    type: "suggestion",
    fixable: "code",
    messages: {
      avoidNewString: "Avoid 'new String()'. Use 'String()' instead.",
    },
  },
  create(context) {
    return {
      NewExpression(node) {
        if (node.callee.name === "String") {
          context.report({
            node,
            messageId: "avoidNewString",
            fix(fixer) {
              const source = context.getSourceCode().getText(node);
              const fixed = source.replace(/^new\s+/, "");
              return fixer.replaceText(node, fixed);
            },
          });
        }
      },
    };
  },
};
JavaScript

→ これで eslint --fix を実行すると、自動的に new String("abc")String("abc") に変換されます。

タイトルとURLをコピーしました