持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第27天,点击查看活动详情
substring()
语法:str.substring(indexStart, indexEnd)
参数:
indexStart:需要截取的第一个字符的索引,座位返回的首字母。
indexEnd:可选。一个0到字符串长度之间的整数,以该数字为索引的字符不包含在街区的字符串内。
描述:
substring提取从indexStart到indexEnd(不包括)之间的字符。
- 如果indexStart等于indexEnd,substring返回一个空字符串。
- 如果省略indexEnd,则substring返回一直到字符串末尾。
- 如果任意参数小于0或者为NaN,则默认被当作0.
- 如果任意参数大于字符串长度,则默认被当作字符串长度。
- 如果indexStart大于indexEnd,则substring的执行效果就像两个参数调换了一样显示最终的结果。
示例:
// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));//前者大于后者
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));NaN被当作0
console.log(anyString.substring(-2,3));//负数被当作0
console.log(anyString.substring(NaN,3));
// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));//前者大于后者
// 输出 ""
console.log(anyString.substring(4,4));//相等返回空字符串
// 输出 "Mozill"
console.log(anyString.substring(0,6));
// 输出 "Mozilla"
console.log(anyString.substring(0,7));//大于总长度,则被当作总长度
console.log(anyString.substring(0,10));
复制代码
splice()
语法:str.slice(beginIndex, endIndex)
参数:
beginIndex:以0为基准,开始提取原字符串中的字符。如果值为负值,会被当作strLength+beginIndex看待(例如:beginIndex是-3,则被看作是strLength-3)
endIndex:可选。以0为基准,结束提取原字符串中的字符。如果省略该参数,splice()会一直提取到字符串末尾。如果该参数为负数,同上(例如是endIndex是-3,则被看作是strLength-3)
描述:
splice()从一个字符串中提取字符串并返回新字符串。在一个字符串中的改变不会影响另一个字符串,也就是说,splice不会修改源字符串(只会返回一个原字符串中部分字符的新字符串)
splice()提取的新字符串包括beginIndex但不包括endIndex.
例子:
var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);
console.log(str2); // 输出:he morn
console.log(str3); // 输出:morning is upon u
console.log(str4); // 输出:is upon us.
console.log(str5); // 输出:""
复制代码
split()
语法:str.split(separator, limit)
参数:
separator:指定表示每个拆分应发生的点的字符串,可以是字符串也可以是正则表达式。
limit:一个整数,限定返回的分割片段数量。当提供此参数时,split方法会在指定分隔符的每次出现时分割该字符串,但在限制条乙方如数组时停止。如果在达到指定限制之前达到字符串的末尾,它可能仍然包括少于限制的条目。新数组中不返回剩下的文本。
描述:
找到分隔符后,将其从字符串中删除,并将子字符串的数组返回。如果没有找到或者省略了分隔符,则该数组包含一个由整个字符串组成的元素。如果分隔符为空字符串,则将str转换为字符数组。如果分隔符出现在字符串的开始或者结尾,或两者都分开,分别以空字符串开头,结尾或两者开始和结束。因此,如果字符串仅由一个分隔符实例组成,则该数组由两个空字符串组成。
示例:
var myString = "Hello 1 word. Sentence number 2.";
var splits = myString.split(/(\d)/);
console.log(splits);
输出:[ "Hello ", "1", " word. Sentence number ", "2", "." ]
上例中,分割的标识为空格,所以,返回已分开空格后的数组。
复制代码
var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);
console.log(splits);
输出["Hello", "World.", "How"]
上例中,`split` 查找字符串中的 0 或多个空格,并返回找到的前 3 个分割元素(splits)。