01、Substr
+ I1 z) L7 i2 q f. u% Q/ w w# ~ 该substr(start, length)方法提取字符串的一部分,从指定的索引处开始,并返回指定数量的字符。$ ]# k5 L9 P4 T* x) c
- const quote = "Winter is coming";
- const part1 = quote.substr(0, 6);
- //Winter
- const part2 = quote.substr(10, 6);
- //coming
请注意,第一个字符在index处为0。该start指数是必需的,但 length是可选的。如果省略,它将提取字符串的其余部分。
( ^" O! w3 i. J' l( g8 n- const quote = "Winter is coming";
- const part = quote.substr(6);
- // is coming
02、Substring 9 Y4 V# V: R, E' ^9 v; p
该substring(start, end)方法返回start和end索引之间的字符串部分。它从start索引处的字符开始到结束,但不包括索引处的字符end。
% b3 m1 G6 C2 ~! T! ~1 x6 A% q- const quote = "We Stand Together";
- const part = quote.substring(3, 8);
- // Stand
如果end省略索引,它将提取到字符串的末尾。
4 |9 m J7 w* I! F3 h. @- const quote = "We Stand Together";
- const part = quote.substring(3);
- // Stand Together
与indexOf方法结合使用,效果会更好。该indexOf方法返回第一个索引,在该索引处可以找到给定的字符串文本,否则返回-1。考虑以下代码在第一个逗号之后提取文本。 ) F# Y7 m V6 `" P! ^
- const quote = "You know nothing, Jon Snow";
- const commaIndex = quote.indexOf(",");
- const part = quote.substring(commaIndex + 1);
- //" Jon Snow"
03、Slice
; G- ~0 P- }, J 该slice(start, end)方法返回start和end索引之间的字符串部分。slice像substring。 2 Z0 s/ Z: v, N: x+ [6 }+ y' O
- const quote = "We Stand Together";
- const part = quote.slice(3, 8);
- // Stand
如果end省略索引,它将提取到字符串的末尾。
: C& X( a+ q1 n$ S, C u- const quote = "We Stand Together";
- const part = quote.slice(3);
- // Stand Together
slice基本上是为了模仿阵列接口而添加的。(数组中有一个同名的方法在两个索引之间提取其一部分,并返回一个新的浅表副本)。 * f" o. V/ `9 U+ R1 p* _ i' L
字符串在JavaScript中是不可变的。所有这些方法都不会更改原始字符串。 |