aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html
blob: 1c42d9925f3fe470b2d94e233efaf1b53dbd025a (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
---
title: String.prototype.replace()
slug: Web/JavaScript/Reference/Global_Objects/String/replace
translation_of: Web/JavaScript/Reference/Global_Objects/String/replace
---
<div>{{JSRef}}</div>

<p><strong><code>replace()</code></strong> 方法會傳回一個新字串,此新字串是透過將原字串與 <code>pattern</code> 比對,以 <code>replacement</code> 取代吻合處而生成。<code>pattern</code> 可以是字串或 {{jsxref("RegExp")}},而 <code>replacement</code> 可以是字串或函式(會在每一次匹配時被呼叫)。</p>

<div class="note">
<p>備註:原始的字串會保持不變。</p>
</div>

<h2 id="語法">語法</h2>

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

<h3 id="參數">參數</h3>

<dl>
 <dt><code>regexp</code> (pattern)</dt>
 <dd>{{jsxref("RegExp")}} 的物件或文字。 被比對出來的部分將會被取代為 <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>The {{jsxref("String")}} that replaces the substring specified by the specified <code>regexp</code> or <code>substr</code> parameter. A number of special replacement patterns are supported; see the "<a href="#指定一個字串為參數">Specifying a string as a parameter</a>" section below.</dd>
 <dt><code>function</code> (replacement)</dt>
 <dd>A function to be invoked to create the new substring to be used to replace the matches to the given <code>regexp</code> or <code>substr</code>. The arguments supplied to this function are described in the "<a href="#指定一個函式為參數">Specifying a function as a parameter</a>" section below.</dd>
</dl>

<h3 id="回傳值">回傳值</h3>

<p>A new string with some or all matches of a pattern replaced by a replacement.</p>

<h2 id="描述">描述</h2>

<p>這個方法不會變更所呼叫的 {{jsxref("String")}}。它只會回傳新的字串。</p>

<p>To perform a global search and replace, include the <code>g</code> switch in the regular expression.</p>

<h3 id="指定一個字串為參數">指定一個字串為參數</h3>

<p>The replacement string can include the following special replacement patterns:</p>

<table class="fullwidth-table">
 <tbody>
  <tr>
   <td class="header">Pattern</td>
   <td class="header">Inserts</td>
  </tr>
  <tr>
   <td><code>$$</code></td>
   <td>Inserts a "$".</td>
  </tr>
  <tr>
   <td><code>$&amp;</code></td>
   <td>Inserts the matched substring.</td>
  </tr>
  <tr>
   <td><code>$`</code></td>
   <td>Inserts the portion of the string that precedes the matched substring.</td>
  </tr>
  <tr>
   <td><code>$'</code></td>
   <td>Inserts the portion of the string that follows the matched substring.</td>
  </tr>
  <tr>
   <td><code>$<em>n</em></code></td>
   <td>Where <code><em>n</em></code> is a positive integer less than 100, inserts the <em>n</em>th parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object.</td>
  </tr>
 </tbody>
</table>

<h3 id="指定一個函式為參數">指定一個函式為參數</h3>

<p>You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do <em>not</em> apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.</p>

<p>The arguments to the function are as follows:</p>

<table class="fullwidth-table">
 <tbody>
  <tr>
   <td class="header">Possible name</td>
   <td class="header">Supplied value</td>
  </tr>
  <tr>
   <td><code>match</code></td>
   <td>The matched substring. (Corresponds to <code>$&amp;</code> above.)</td>
  </tr>
  <tr>
   <td><code>p1, p2, ...</code></td>
   <td>The <em>n</em>th parenthesized submatch string, provided the first argument to <code>replace()</code> was a {{jsxref("RegExp")}} object. (Corresponds to <code>$1</code>, <code>$2</code>, etc. above.) For example, if <code>/(\a+)(\b+)/</code>, was given, <code>p1</code> is the match for <code>\a+</code>, and <code>p2</code> for <code>\b+</code>.</td>
  </tr>
  <tr>
   <td><code>offset</code></td>
   <td>The offset of the matched substring within the whole string being examined. (For example, if the whole string was <code>'abcd'</code>, and the matched substring was <code>'bc'</code>, then this argument will be 1.)</td>
  </tr>
  <tr>
   <td><code>string</code></td>
   <td>The whole string being examined.</td>
  </tr>
 </tbody>
</table>

<p>(The exact number of arguments will depend on whether the first argument was a {{jsxref("RegExp")}} object and, if so, how many parenthesized submatches it specifies.)</p>

<p>The following example will set <code>newString</code> to <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="範例">範例</h2>

<h3 id="於_replace()_中定義正則表示式"><code>replace()</code> 中定義正則表示式</h3>

<p>下例的正規表達式被定義為 <code>replace()</code>、並包含了忽略大小寫的 flag。</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>

<p>上例會顯示「Twas the night before Christmas...」</p>

<h3 id="使用_global_及_ignore_來配合_replace()">使用 <code>global</code><code>ignore</code> 來配合 <code>replace()</code></h3>

<p>Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits <code>replace()</code> to replace each occurrence of 'apples' in the string with '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="替換字串中的單字">替換字串中的單字</h3>

<p>下例程式將切換字串內的單字。對 replacement text 而言,程式會使用 <code>$1</code> and <code>$2</code> 的 replacement pattern。</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="使用行內函式來修改匹配的字元">使用行內函式來修改匹配的字元</h3>

<p>In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.</p>

<p>The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.</p>

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

<p>Given <code>styleHyphenFormat('borderTop')</code>, this returns 'border-top'.</p>

<p>Because we want to further transform the <em>result</em> of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.</p>

<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&amp;'.toLowerCase());  // won't work
</pre>

<p>This is because <code>'$&amp;'.toLowerCase()</code> would be evaluated first as a string literal (resulting in the same <code>'$&amp;'</code>) before using the characters as a pattern.</p>

<h3 id="將華氏溫度置換成攝氏溫度">將華氏溫度置換成攝氏溫度</h3>

<p>The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.</p>

<p>The regular expression <code>test</code> checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, <code>p1</code>. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the <code>f2c()</code> function. <code>f2c()</code> then returns the Celsius number. This function approximates Perl's <code>s///e</code> flag.</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="利用行內函式及正則表示式來避免使用_for_迴圈">利用行內函式及正則表示式來避免使用 <code>for</code> 迴圈</h3>

<p>The following example takes a string pattern and converts it into an array of objects.</p>

<p><strong>Input:</strong></p>

<p>A string made out of the characters <code>x</code>, <code>-</code> and <code>_</code></p>

<pre>x-x_
x---x---x---x---
x-xxx-xx-x-
x_x_x___x___x___
</pre>

<p><strong>Output:</strong></p>

<p>An array of objects. An <code>'x'</code> denotes an <code>'on'</code> state, a <code>'-'</code> (hyphen) denotes an <code>'off'</code> state and an <code>'_'</code> (underscore) denotes the length of an <code>'on'</code> state.</p>

<pre class="brush: json">[
  { on: true, length: 1 },
  { on: false, length: 1 },
  { on: true, length: 2 }
  ...
]
</pre>

<p><strong>Snippet:</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>This snippet generates an array of 3 objects in the desired format without using a <code>for</code> loop.</p>

<h2 id="規範">規範</h2>

<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>Initial definition. Implemented in 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="瀏覽器相容性">瀏覽器相容性</h2>

<p class="hidden">本相容性表格使用結構化資料自動產生。想要貢獻的話,請看看 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 並發個 PR。</p>

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

<h2 id="Firefox-specific_notes">Firefox-specific notes</h2>

<ul>
 <li>Starting with Gecko 27 {{geckoRelease(27)}}, this method has been adjusted to conform with the ECMAScript specification. When <code>replace()</code> is called with a global regular expression, the {{jsxref("RegExp.lastIndex")}} property (if specified) will be reset to <code>0</code> ({{bug(501739)}}).</li>
 <li>Starting with Gecko 39 {{geckoRelease(39)}}, the non-standard <code>flags</code> argument is deprecated and throws a console warning ({{bug(1142351)}}).</li>
 <li>Starting with Gecko 47 {{geckoRelease(47)}}, the non-standard <code>flags</code> argument is no longer supported in non-release builds and will soon be removed entirely ({{bug(1245801)}}).</li>
 <li>Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard <code>flags</code> argument is no longer supported ({{bug(1108382)}}).</li>
</ul>

<h2 id="參見">參見</h2>

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