A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape below:

RegExp.escape() - JavaScript | MDN

RegExp.escape()

Baseline 2025

Newly available

RegExp.escape() は静的メソッドで、文字列内の潜在的な正規表現構文文字をエスケープし、リテラルパターンとして RegExp() コンストラクターで安全に使用できる新しい文字列を返します。

ユーザーが提供したコンテンツを含む RegExp を動的に作成する場合は、この関数を使用して入力を無害化することを検討してください(入力が実際に正規表現構文を含むように意図されている場合を除く)。また、例えば、 String.prototype.replaceAll() を使用して、すべての構文文字の前に \ を挿入するなどして、その機能を再実装しようとしないでください。 RegExp.escape() は、手作業で作成したコードではおそらく達成できないであろう、複数のエッジケース/コンテキストで動作するエスケープシーケンスを使用するように設計されています。

構文 引数
string

エスケープする文字列です。

返値

RegExp() コンストラクターのリテラルパターンとして安全に使用できる新しい文字列。すなわち、入力文字列内の次の置き換えが行われます。

例外
TypeError

string が文字列ではない場合に発生します。

例 RegExp.escape() の使用

次の例は、RegExp.escape() メソッドのさまざまな入力と出力を示しています。

RegExp.escape("Buy it. use it. break it. fix it.");
// "\\x42uy\\x20it\\.\\x20use\\x20it\\.\\x20break\\x20it\\.\\x20fix\\x20it\\."
RegExp.escape("foo.bar"); // "\\x66oo\\.bar"
RegExp.escape("foo-bar"); // "\\x66oo\\x2dbar"
RegExp.escape("foo\nbar"); // "\\x66oo\\nbar"
RegExp.escape("foo\uD800bar"); // "\\x66oo\\ud800bar"
RegExp.escape("foo\u2028bar"); // "\\x66oo\\u2028bar"
RegExp.escape() と RegExp コンストラクターの使用

RegExp.escape() の主な使用例は、文字列をより大きな正規表現パターンに埋め込み、その文字列が正規表現の構文ではなくリテラルパターンとして確実に保持したい場合です。URL を置換する次の単純な例を考えてみましょう。

function removeDomain(text, domain) {
  return text.replace(new RegExp(`https?://${domain}(?=/)`, "g"), "");
}

const input =
  "Consider using [RegExp.escape()](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape) to escape special characters in a string.";
const domain = "developer.mozilla.org";
console.log(removeDomain(input, domain));
// Consider using [RegExp.escape()](/ja/docs/Web/JavaScript/Reference/Global_Objects/RegExp/escape) to escape special characters in a string.

上記の domain を挿入すると、正規表現リテラル https?://developer.mozilla.org(?=/) となります。ここで、 "." 文字は正規表現のワイルドカード文字です。これは、文字列が "." の代わりに何か文字を持つ文字列と一致することを意味しており、例えば、 developer-mozilla-org などが該当します。したがって、次のテキストも誤って変更されてしまいます。

const input =
  "This is not an MDN link: https://developer-mozilla.org/, be careful!";
const domain = "developer.mozilla.org";
console.log(removeDomain(input, domain));
// This is not an MDN link: /, be careful!

これを修正するには、 RegExp.escape() を使用して、ユーザー入力が確実にリテラルパターンとして扱われるようにします。

function removeDomain(text, domain) {
  return text.replace(
    new RegExp(`https?://${RegExp.escape(domain)}(?=/)`, "g"),
    "",
  );
}

これでこの関数は意図通りに動作し、 developer-mozilla.org の URL を変換しなくなります。

仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4