aboutsummaryrefslogtreecommitdiff
path: root/files/ja/web/javascript/reference/global_objects/string/replace/index.html
blob: 4145550f59935bb2ecd55be611a9c328928757e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
---
title: String.prototype.replace()
slug: Web/JavaScript/Reference/Global_Objects/String/replace
tags:
  - Expressions
  - JavaScript
  - Methods
  - Prototype
  - Reference
  - Regular
  - String
translation_of: Web/JavaScript/Reference/Global_Objects/String/replace
---
<div>{{JSRef}}</div>

<p><span class="seoSummary"><strong><code>replace()</code></strong> メソッドは、<code>pattern</code> にマッチした文字列の一部またはすべてを <code>replacement</code> で置き換えた新しい文字列を返します。</span><code>pattern</code> は文字列または {{jsxref("RegExp")}}<code>replacement</code> は文字列または各マッチで呼び出される関数です。<code>pattern</code> が文字列の場合、最初に一致した箇所のみを置き換えます。</p>

<p>元の文字列は変更されません。</p>

<div>{{EmbedInteractiveExample("pages/js/string-replace.html")}}</div>



<h2 id="Syntax" name="Syntax">構文</h2>

<pre class="syntaxbox"><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre>

<h3 id="Parameters" name="Parameters">引数</h3>

<dl>
 <dt><code>regexp</code> (pattern)</dt>
 <dd>{{jsxref("RegExp")}} オブジェクト、またはリテラルです。マッチすると、第2引数の <code>newSubStr</code> または <code>function</code> の戻り値と置き換えられます。</dd>
 <dt><code>substr</code> (pattern)</dt>
 <dd><code>newSubStr</code> に置き換えられる {{jsxref("String")}} です。これは逐次的な文字列として扱われ、正規表現としては解釈されません。最初に出てきたものだけが置き換えられます。</dd>
 <dt><code>newSubStr</code> (replacement)</dt>
 <dd><code>regexp</code><code>substr</code> パラメーターで指定される部分文字列を置換する {{jsxref("String")}} です。数々の特別な置換パターンがサポートされます。下記の「{{anch("Specifying_a_string_as_a_parameter", "引数としての文字列の指定")}}」節を見てください。</dd>
 <dt><code>function</code> (replacement)</dt>
 <dd>新しい部分文字列を生成するために実行される関数で、<code>regexp</code><code>substr</code> でマッチしたものを置き換えるのに使われます。この関数に渡される引数は下記の「{{anch("Specifying_a_function_as_a_parameter", "引数としての関数の指定")}}」で述べられています。</dd>
</dl>

<h3 id="Return_value" name="Return_value">戻り値</h3>

<p>パターンにマッチした部分文字列の一部またはすべてを置換文字列で置き換えた新しい文字列です。</p>

<h2 id="Description" name="Description">詳細</h2>

<p>このメソッドは、それを呼び出した {{jsxref("String")}} オブジェクトを変化させません。戻り値として新しい文字列を返します。</p>

<p>グローバルな検索と置換を動作させるためには、正規表現に <code>g</code> フラグを含める必要があります。</p>

<h3 id="Specifying_a_string_as_a_parameter" name="Specifying_a_string_as_a_parameter">引数としての文字列の指定</h3>

<p>置換文字列には以下の特殊な置換パターンを含めることができます。</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">パターン</td>
   <td class="header">挿入</td>
  </tr>
  <tr>
   <td><code>$$</code></td>
   <td>"$" を挿入します。</td>
  </tr>
  <tr>
   <td><code>$&amp;</code></td>
   <td>マッチした部分文字列を挿入します。</td>
  </tr>
  <tr>
   <td><code>$`</code></td>
   <td>マッチした部分文字列の直前の文字列の部分を挿入します。</td>
  </tr>
  <tr>
   <td><code>$'</code></td>
   <td>マッチした部分文字列の直後の文字列の部分を挿入します。</td>
  </tr>
  <tr>
   <td><code>$<em>n</em></code></td>
   <td><code><em>n</em></code> は 100 未満の正の整数です。第一引数が {{jsxref("RegExp")}} オブジェクトだった場合に <em>n</em> 番目の括弧でキャプチャされた文字列を挿入します。1, 2, ... でインデックスされることに注意してください。</td>
  </tr>
 </tbody>
</table>

<h3 id="Specifying_a_function_as_a_parameter" name="Specifying_a_function_as_a_parameter">引数としての関数の指定</h3>

<p>第二引数として関数を指定することができます。このとき、関数はマッチが完了された後に実行されます。関数呼び出しの結果(返り値)は、置換文字列として使われます(注記: 上記の特殊な置換パターンはこの場合には適用<strong>されません</strong>)。第一引数の正規表現がグローバルだと、置換されるべきマッチごとに関数が複数回実行されうることに注意してください。</p>

<p>関数に与えられる引数は次の通りです。</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">名前</td>
   <td class="header">与えられる値</td>
  </tr>
  <tr>
   <td><code>match</code></td>
   <td>マッチした部分文字列(上記の <code>$&amp;</code> に対応)です。</td>
  </tr>
  <tr>
   <td><code>p1, p2, ...</code></td>
   <td><code>replace()</code> の第一引数が {{jsxref("RegExp")}} オブジェクトだった場合、<em>n</em> 番目の括弧でキャプチャされたグループの文字列(上記の <code>$1</code>, <code>$2</code>, などに対応)です。例えば <code>/(\a+)(\b+)/</code> が与えられた場合、<code>p1</code><code>\a+</code> に対するマッチ、<code>p2</code><code>\b+</code> に対するマッチとなります。</td>
  </tr>
  <tr>
   <td><code>offset</code></td>
   <td>マッチした部分文字列の、分析中の文字列全体の中でのオフセットです(例えば、文字列全体が <code>'abcd'</code> で、マッチした部分文字列が <code>'bc'</code> ならば、この引数は 1 となります)。</td>
  </tr>
  <tr>
   <td><code>string</code></td>
   <td>分析中の文字列全体です。</td>
  </tr>
 </tbody>
</table>

<p>(引数の正確な個数は、第一引数が {{jsxref("RegExp")}} オブジェクトかどうか、そうならばさらに括弧でキャプチャされるサブマッチがいくつ指定されているかに依ります。)</p>

<p>以下の例は <code>newString</code><code>'abc - 12345 - #$*%'</code> をセットします。</p>

<pre class="brush: js">function replacer(match, p1, p2, p3, offset, string) {
  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
  return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%
</pre>

<h2 id="Examples" name="Examples"></h2>

<h3 id="Defining_the_regular_expression_in_replace()" name="Defining_the_regular_expression_in_replace()"><code>replace()</code> で正規表現を利用する</h3>

<p>以下の例では、<code>replace</code> メソッドで正規表現を利用しています。</p>

<pre class="brush: js">var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);  // Twas the night before Christmas...
</pre>

<h3 id="Using_global_and_ignore_with_replace()" name="Using_global_and_ignore_with_replace()"><code>ignore</code> フラグと <code>global</code> フラグの利用</h3>

<p>グローバルな置換は正規表現だけで行われます。以下の例では、正規表現で大文字と小文字の違いを無視するフラグ (<code>i</code>) とグローバルマッチのフラグ (<code>g</code>)を利用し <code>replace()</code> は'apples'が出てくるたびに'oranges'に置換します。</p>

<pre class="brush: js">var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr);  // oranges are round, and oranges are juicy.
</pre>

<p>この出力は 'oranges are round, and oranges are juicy' となります。</p>

<h3 id="Switching_words_in_a_string" name="Switching_words_in_a_string">文字列内の単語の交換</h3>

<p>文字列内の単語の位置を交換します。<code>$1</code><code>$2</code> を置き換えるパターンを使用しています。</p>

<pre class="brush: js">var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);  // Smith, John
</pre>

<p>この出力は 'Smith, John' となります。</p>

<h3 id="Using_an_inline_function_that_modifies_the_matched_characters" name="Using_an_inline_function_that_modifies_the_matched_characters">マッチした文字を修正するインライン関数の使用</h3>

<p>次の例では、文字列内に出現する大文字のすべては小文字に変換され、ハイフンがマッチした位置の直前に挿入されます。ここで重要なことは、追加の操作は、マッチしたアイテムが置換されて戻される前に必要とされるということです。</p>

<p>置換する関数はマッチした断片をその関数の引数として適用します。そして、その引数を大文字小文字変形し、戻り値の直前にハイフンを連結します。</p>

<pre class="brush: js">function styleHyphenFormat(propertyName) {
  function upperToHyphenLower(match, offset, string) {
    return (offset &gt; 0 ? '-' : '') + match.toLowerCase();
  }
  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
</pre>

<p><code>styleHyphenFormat('borderTop')</code>を入力すると 'border-top'を返します。</p>

<p>最終的な置換が作成される前にサブマッチの<em>結果</em> をさらに変形したい場合、関数を使わなくてはなりません。これは、<code>toLowerCase()</code> メソッドの前にマッチを評価することを強制します。関数無しにこれをマッチに使用した場合、その <code>toLowerCase()</code> メソッドは効果がないでしょう。</p>

<pre class="brush:js">var newString = propertyName.replace(/[A-Z]/, '-' + '$&amp;'.toLowerCase());  // 動作しないでしょう</pre>

<p>これは、<code>'$&amp;'.toLowerCase()</code> は、まずその文字がパターンとして使用される前に (<code>'$&amp;'</code> という結果である ) 文字列リテラルとして評価されるだろうからです。</p>

<h3 id="Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent" name="Replacing_a_Fahrenheit_degree_with_its_Celsius_equivalent">華氏温度を同等の摂氏温度と置き換える</h3>

<p>以下の例は、ある華氏温度をそれと同等の摂氏温度と置き換えます。その華氏温度は F で終わる数でなければなりません。その関数は C で終わる摂氏を返します。例えば、入力される数が 212F である場合、その関数は 100C を返します。入力される数が 0F であった場合、その関数は -17.77777777777778C を返します。</p>

<p>その正規表現 <code>test</code> は、任意の数が F で終わっているかチェックします。華氏温度の数は、関数の 第二引数 <code>p1</code> を通して、その関数にアクセスできます。その関数は文字列内で渡された華氏温度をベースとした摂氏の数を <code>f2c</code> にセットします。それから、<code>f2c</code> は、摂氏の数を返します。この関数は Perl の s///e フラグ {{訳注('s は substitute (置換する)の略。e は evaluate(評価する)の略です。詳細は <a href="http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators" title="perlop - perldoc.perl.org">perlop の Regexp Quote-Like Operators の項</a>(<a href="http://perldoc.jp/docs/perl/perlop.pod#Regexp32Quote-Like32Operators" title="perlop - Perl の演算子と優先順位 - perldoc.jp - #正規表現のクォート風の演算子">※perldoc.jp による日本語訳</a>)を参照してください。')}} と似ています。</p>

<pre class="brush: js">function f2c(x) {
  function convert(str, p1, offset, s) {
    return ((p1 - 32) * 5/9) + 'C';
  }
  var s = String(x);
  var test = /(-?\d+(?:\.\d*)?)F\b/g;
  return s.replace(test, convert);
}
</pre>

<h3 id="Use_an_inline_function_with_a_regular_expression_to_avoid_for_loops" name="Use_an_inline_function_with_a_regular_expression_to_avoid_for_loops">インライン関数と正規表現で <code>for</code> ループを回避する</h3>

<p>次の例では、あるパターンを持つ文字列を解析してオブジェクトの配列に変換します。</p>

<p><strong>入力:</strong></p>

<p><code>x</code>, <code>-</code>, <code>_</code> からなる文字列です。</p>

<pre class="line-numbers  language-html"><code class="language-html">x-x_
x---x---x---x---
x-xxx-xx-x-
x_x_x___x___x___</code></pre>

<p><strong>出力ルール:</strong></p>

<p><code>'x'</code><code>'on'</code> への切り替えを、<code>'-'</code> (ハイフン) は <code>'off'</code> への切り替えを表すとし、<code>'_'</code> (アンダースコア) は x の後に続いて <code>'on'</code> の長さを表すものとします。on と off の切り替わりをオブジェクトの配列で返します。</p>

<pre class="brush: json">[
  { on: true, length: 1 },   // 一番最初の "x" で on になります。
  { on: false, length: 1 },  // その次の "-" で off になります。
  { on: true, length: 2 }    // その次の "x" で on になり、"_" が一つ続いているため、長さは 2 になります。
  ...
]
</pre>

<p><strong>スニペット</strong><strong>:</strong></p>

<pre class="brush: js">var str = 'x-x_';
var retArr = [];
str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
  if (p1) { retArr.push({ on: true, length: p1.length }); }
  if (p2) { retArr.push({ on: false, length: 1 }); }
});

console.log(retArr);
</pre>

<p>このスニペットは <code>for</code> を使わずに、上記の入出力ルールを満たす 3 オブジェクトからなる配列を生成します。</p>

<h2 id="See_also" name="See_also">仕様</h2>

<ul>
</ul>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">仕様書</th>
   <th scope="col">策定状況</th>
   <th scope="col">コメント</th>
  </tr>
  <tr>
   <td>{{SpecName('ES3')}}</td>
   <td>{{Spec2('ES3')}}</td>
   <td>初期定義。JavaScript 1.2 で実装される。</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2>

<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>

<p>{{Compat("javascript.builtins.String.replace")}}</p>

<h2 id="Firefox-specific_notes" name="Firefox-specific_notes">Firefox 固有の注記</h2>

<ul>
 <li><code>flags</code> は Gecko のみで利用できる非標準の第3引数です : <var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubStr</var>|<var>function, flags</var>)</li>
 <li>Gecko 27 {{geckoRelease(27)}} 以降、このメソッドは ECMAScript 標準に準拠するために補正されました。<code>replace()</code> がグローバルの正規表現とともに呼び出された場合、{{jsxref("RegExp.lastIndex")}} プロパティが(もし指定されていたなら)<code>0</code> にリセットされます ({{bug(501739)}})。</li>
 <li>Gecko 39 {{geckoRelease(39)}} 以降、<code>flags</code> 引数は非推奨となり、コンソールに警告を投げます ({{bug(1142351)}})。</li>
 <li>Gecko 47 {{geckoRelease(47)}} 以降、非標準の <code>flags</code> 引数は非リリース版でサポートされず、もうすぐ完全に削除されます ({{bug(1245801)}}).</li>
 <li>Gecko 49 {{geckoRelease(49)}} 以降、非標準の <code>flags</code> 引数はもうサポートされません ({{bug(1108382)}}).</li>
</ul>

<h2 id="See_also" name="See_also">関連情報</h2>

<ul>
 <li>{{jsxref("String.prototype.match()")}}</li>
 <li>{{jsxref("RegExp.prototype.exec()")}}</li>
 <li>{{jsxref("RegExp.prototype.test()")}}</li>
</ul>