aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/string/split/index.html
blob: c1dee44c87eafff853bd92eefc391869511569d0 (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
---
title: String.prototype.split()
slug: Web/JavaScript/Reference/Global_Objects/String/split
tags:
  - JavaScript
  - Method
  - Prototype
  - Reference
  - Regular Expressions
  - String
translation_of: Web/JavaScript/Reference/Global_Objects/String/split
---
<p>{{JSRef}}</p>

<p><code><strong>split() </strong></code>方法使用指定的分隔符字符串将一个{{jsxref("String")}}对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。 </p>

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



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

<pre class="syntaxbox"><code><em>str.split([separator[, limit]])</em></code>
</pre>

<div class="blockIndicator warning">
<p>注意:如果使用空字符串(“)作为分隔符,则字符串不是在每个用户感知的字符(图形素集群)之间,也不是在每个Unicode字符(代码点)之间,而是在每个UTF-16代码单元之间。这会摧毁代理对。还请参见<a href="https://stackoverflow.com/questions/4547609/how-do-you-get-a-string-to-a-character-array-in-javascript/34717402#34717402">how do you get a string to a character array in javascript</a></p>
</div>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>separator</code></dt>
 <dd>指定表示每个拆分应发生的点的字符串。<code>separator</code> 可以是一个字符串或<a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp" title="JavaScript/Reference/Global_Objects/RegExp">正则表达式</a>。 如果纯文本分隔符包含多个字符,则必须找到整个字符串来表示分割点。如果在str中省略或不出现分隔符,则返回的数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str原字符串中每个字符的数组形式返回。</dd>
 <dt><code>limit</code></dt>
 <dd>一个整数,限定返回的分割片段数量。当提供此参数时,split 方法会在指定分隔符的每次出现时分割该字符串,但在限制条目已放入数组时停止。如果在达到指定限制之前达到字符串的末尾,它可能仍然包含少于限制的条目。新数组中不返回剩下的文本。</dd>
</dl>

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

<p>返回源字符串以分隔符出现位置分隔而成的一个 {{jsxref("Array")}} </p>

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

<p>找到分隔符后,将其从字符串中删除,并将子字符串的数组返回。如果没有找到或者省略了分隔符,则该数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str转换为字符数组。如果分隔符出现在字符串的开始或结尾,或两者都分开,分别以空字符串开头,结尾或两者开始和结束。因此,如果字符串仅由一个分隔符实例组成,则该数组由两个空字符串组成。</p>

<p>如果分隔符是包含捕获括号的正则表达式,则每次分隔符匹配时,捕获括号的结果(包括任何未定义的结果)将被拼接到输出数组中。但是,并不是所有浏览器都支持此功能。</p>

<p>{{Note("当字符串为空时,split()返回一个包含一个空字符串的数组,而不是一个空数组,如果字符串和分隔符都是空字符串,则返回一个空数组。")}}</p>

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

<h3 id="Example_Using_split" name="Example:_Using_split">使用 <code>split()</code></h3>

<p>下例定义了一个函数:根据指定的分隔符将一个字符串分割成一个字符串数组。分隔字符串后,该函数依次输出原始字符串信息,被使用的分隔符,返回数组元素的个数,以及返回数组中所有的元素。</p>

<pre class="brush: js">function splitString(stringToSplit, separator) {
  var arrayOfStrings = stringToSplit.split(separator);

  console.log('The original string is: "' + stringToSplit + '"');
  console.log('The separator is: "' + separator + '"');
  console.log("The array has " + arrayOfStrings.length + " elements: ");

  for (var i=0; i &lt; arrayOfStrings.length; i++)
    console.log(arrayOfStrings[i] + " / ");
}

var tempestString = "Oh brave new world that has such people in it.";
var monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

var space = " ";
var comma = ",";

splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
</pre>

<p>上例输出下面结果:</p>

<pre>The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. /

The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it. /

The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec /
</pre>

<h3 id="Example_Removing_spaces_from_a_string" name="Example:_Removing_spaces_from_a_string">移出字符串中的空格</h3>

<p>下例中,<code>split()</code> 方法会查找“0 或多个空白符接着的分号,再接着 0 或多个空白符”模式的字符串,找到后,就将空白符从字符串中移除,<code>nameList</code><code>split</code> 的返回数组。</p>

<pre class="brush: js">var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";

console.log(names);

var re = /\s*(?:;|$)\s*/;
var nameList = names.split(re);

console.log(nameList);
</pre>

<p>上例输出两行,第一行输出原始字符串,第二行输出结果数组。</p>

<pre><code>Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]</code>
</pre>

<h3 id="Example_Returning_a_limited_number_of_splits" name="Example:_Returning_a_limited_number_of_splits">限制返回值中分割元素数量</h3>

<p>下例中,<code>split</code> 查找字符串中的 0 或多个空格,并返回找到的前 3 个分割元素(splits)。</p>

<pre class="brush: js">var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);

console.log(splits);
</pre>

<p>上例输出:</p>

<pre><code>["Hello", "World.", "How"]</code></pre>

<h3 id="Example_Capturing_parentheses" name="Example:_Capturing_parentheses">靠正则来分割使结果中包含分隔块</h3>

<p>如果 <code>separator</code> 包含捕获括号(capturing parentheses),则其匹配结果将会包含在返回的数组中。</p>

<pre class="brush: js">var myString = "Hello 1 word. Sentence number 2.";
var splits = myString.split(/(\d)/);

console.log(splits);
</pre>

<p>上例输出:</p>

<pre><code>[ "Hello ", "1", " word. Sentence number ", "2", "." ]</code></pre>

<h3 id="使用一个数组来作为分隔符">使用一个数组来作为分隔符</h3>

<pre><code>const myString = 'this|is|a|Test';
const splits = myString.split(['|']);

console.log(splits); //["this", "is", "a", "Test"]

const myString = 'ca,bc,a,bca,bca,bc';

const splits = myString.split(['a','b']);
// myString.split(['a','b']) is same as myString.split(String(['a','b']))

console.log(splits);  //["c", "c,", "c", "c", "c"]</code></pre>

<h3 id="用split来颠倒字符串顺序">用split()来颠倒字符串顺序</h3>

<div class="blockIndicator warning">
<p>注意这并非一种很健壮的逆转字符串的方法:</p>

<pre><code>const str = 'asdfghjkl';
const strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
// split() returns an array on which reverse() and join() can be applied</code></pre>

<p>如果字符串包含图形素集群,即使使用Unicode感知的拆分(use for example <a href="https://github.com/mathiasbynens/esrever">esrever</a> instead),也不能工作。</p>

<pre><code>const str = 'résumé';
const strReverse = str.split(/(?:)/u).reverse().join('');
// =&gt; "́emuśer"</code></pre>

<p>Bonus: use {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} operator to test if the original string was palindrome.</p>
</div>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>ECMAScript 3rd Edition.</td>
   <td>Standard</td>
   <td>Initial definition.<br>
    Implemented in JavaScript 1.1</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

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

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

<h2 id="See_also" name="See_also">相关链接</h2>

<ul>
 <li>{{jsxref("String.prototype.charAt()")}}</li>
 <li>{{jsxref("String.prototype.indexOf()")}}</li>
 <li>{{jsxref("String.prototype.lastIndexOf()")}}</li>
 <li>{{jsxref("Array.prototype.join()")}}</li>
</ul>