aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/regexp/n/index.html
blob: 4b0dc3f2c8a0a2e5d47f149b838e70592c87ff7d (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
---
title: RegExp.$1-$9
slug: Web/JavaScript/Reference/Global_Objects/RegExp/n
translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/n
---
<div>{{JSRef}} {{non-standard_header}}</div>

<p>非标准<strong>$1, $2, $3, $4, $5, $6, $7, $8, $9 </strong>属性是包含括号子串匹配的正则表达式的静态和只读属性。</p>

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

<pre class="syntaxbox"><code><var>RegExp</var>.$1
RegExp.$2</code>
RegExp.$3
RegExp.$4
RegExp.$5
RegExp.$6
RegExp.$7
RegExp.$8
RegExp.$9
</pre>

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

<p>$1, ..., $9 属性是静态的, 他不是独立的正则表达式属性. 所以, 我们总是像这样子使用他们<code>RegExp.$1</code>, ..., <code>RegExp.$9</code>.</p>

<p>属性的值是只读的而且只有在正确匹配的情况下才会改变.</p>

<p>括号匹配项是无限的, 但是RegExp对象能捕获的只有九个. 你可以通过返回一个数组索引来取得所有的括号匹配项.</p>

<p>这些属性可以在{{jsxref("String.replace")}} 方法中替换字符串. 在这种情况下, 不用在前面加上RegExp。下面的例子将详细说明. 当正则表达式中不包含括号, 脚本中的 <code>$n</code>'s 就是字面上的意思 (当n是正整数).</p>

<h2 id="例子">例子</h2>

<h3 id="n_在_String.replace中的应用"><code>$n</code> 在 <code>String.replace中的应用</code></h3>

<p>以下脚本用 {{jsxref("String.prototype.replace()", "replace()")}} 方法去匹配一个first last格式的 name{{jsxref("String")}} 实例 输出last first格式. 在替换文本里, 脚本用 <code>$1</code> 和 <code>$2</code> 表示正则表达式中的括号匹配项的结果.</p>

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

<h2 id="技术指标">技术指标</h2>

<p>非标准. 不属于当前的任何规范.</p>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

{{Compat}}

<h2 id="参见">参见</h2>

<ul>
 <li>{{non-standard_inline}} {{jsxref("RegExp.input", "RegExp.input ($_)")}}</li>
 <li>{{non-standard_inline}} {{jsxref("RegExp.lastMatch", "RegExp.lastMatch ($&amp;)")}}</li>
 <li>{{non-standard_inline}} {{jsxref("RegExp.lastParen", "RegExp.lastParen ($+)")}}</li>
 <li>{{non-standard_inline}} {{jsxref("RegExp.leftContext", "RegExp.leftContext ($`)")}}</li>
 <li>{{non-standard_inline}} {{jsxref("RegExp.rightContext", "RegExp.rightContext ($')")}}</li>
</ul>