Javascript-string-replace

提供:Dev Guides
移動先:案内検索

JavaScript文字列-replace()メソッド

説明

このメソッドは、正規表現と文字列の一致を検出し、一致した部分文字列を新しい部分文字列で置き換えます。

置換文字列には、次の特別な置換パターンを含めることができます-

Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n or $nn Where n *or nn are decimal digits, inserts the n*th parenthesized submatch string, provided the first argument was a RegExp object.

構文

replace()メソッドを使用する構文は次のとおりです-

string.replace(regexp/substr, newSubStr/function[, flags]);

引数の詳細

  • regexp - RegExp オブジェクト。 一致は、パラメーター#2の戻り値に置き換えられます。
  • substr - newSubStr に置き換えられる文字列。
  • newSubStr -パラメータ#1から受け取った部分文字列を置き換える文字列。
  • function -新しい部分文字列を作成するために呼び出される関数。
  • flags -RegExpフラグの任意の組み合わせを含む文字列: g -グローバル一致、 i -大文字と小文字を区別しない、 m -複数行にわたる一致。 このパラメーターは、最初のパラメーターがストリングの場合にのみ使用されます。

戻り値

単に新しい変更された文字列を返します。

次の例を試してください。

<html>
   <head>
      <title>JavaScript String replace() Method</title>
   </head>

   <body>
      <script type = "text/javascript">
         var re =/apples/gi;
         var str = "Apples are round, and apples are juicy.";
         var newstr = str.replace(re, "oranges");
         document.write(newstr );
      </script>
   </body>
</html>

出力

oranges are round, and oranges are juicy.

次の例を試してください。文字列内の単語を切り替える方法を示しています。

<html>
   <head>
      <title>JavaScript String replace() Method</title>
   </head>

   <body>
      <script type = "text/javascript">
         var re =/(\w+)\s(\w+)/;
         var str = "zara ali";
         var newstr = str.replace(re, "$2, $1");
         document.write(newstr);
      </script>
   </body>
</html>

出力

ali, zara