split
方法将字符串拆分为字符串数组。它接受分隔符的参数,分隔符可以是用于分解字符串或正则表达式的字符。例如,如果分隔符是空格,则会得到一个单词数组,如果分隔符是空字符串,则会得到字符串中每个字符的数组。下面是两个用空格分隔一个字符串的例子,然后用正则表达式用数字分割另一个字符串: var str =“Hello World”;由于字符串是不可变的,因此
var bySpace = str.split(“”);
//将bySpace设置为[“Hello”,“World”]
var otherString =“How9are7you2today”;
var byDigits = otherString.split(/ \ d /);
//将byDigits设置为[“How”,“are”,“you”,“today”]
split
方法可以更轻松地使用它们。 splitify
函数内的split
方法将str
拆分为单词数组。该函数应该返回数组。请注意,单词并不总是用空格分隔,并且数组不应包含标点符号。 split
方法。
testString: 'assert(code.match(/\.split/g), "Your code should use the split
method.");'
- text: 'splitify("Hello World,I-am code")
应返回["Hello", "World", "I", "am", "code"]
。'
testString: 'assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"]), "splitify("Hello World,I-am code")
should return ["Hello", "World", "I", "am", "code"]
.");'
- text: 'splitify("Earth-is-our home")
应该返回["Earth", "is", "our", "home"]
。'
testString: 'assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"]), "splitify("Earth-is-our home")
should return ["Earth", "is", "our", "home"]
.");'
- text: 'splitify("This.is.a-sentence")
应该返回["This", "is", "a", "sentence"]
。'
testString: 'assert(JSON.stringify(splitify("This.is.a-sentence")) === JSON.stringify(["This", "is", "a", "sentence"]), "splitify("This.is.a-sentence")
should return ["This", "is", "a", "sentence"]
.");'
```