String.prototype.slice()
åºçº¿
广æ³å¯ç¨
èª 2015å¹´7æ èµ·ï¼æ¤ç¹æ§å·²å¨ä¸»æµæµè§å¨ä¸å¾å°æ¯æï¼å¯å¨å¤§å¤æ°è®¾å¤åæµè§å¨çæ¬ä¸æ£å¸¸ä½¿ç¨ã
slice() æ¹æ³æåå符串çä¸é¨åï¼å¹¶å°å
¶ä½ä¸ºæ°å符串è¿åï¼èä¸ä¿®æ¹åå§å符串ã
å°è¯ä¸ä¸
const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.slice(31));
// Expected output: "the lazy dog."
console.log(str.slice(4, 19));
// Expected output: "quick brown fox"
console.log(str.slice(-4));
// Expected output: "dog."
console.log(str.slice(-9, -5));
// Expected output: "lazy"
è¯æ³
slice(indexStart)
slice(indexStart, indexEnd)
åæ°
indexStart-
è¦è¿åçåå符串ä¸å å«ç第ä¸ä¸ªå符çç´¢å¼ã
indexEndå¯é-
è¦è¿åçååç¬¦ä¸²ä¸æé¤ç第ä¸ä¸ªå符çç´¢å¼ã
è¿åå¼
ä¸ä¸ªå 嫿åçåç¬¦ä¸²çæ®µçæ°å符串ã
æè¿°
slice() æ¹æ³ä»ä¸ä¸ªåç¬¦ä¸²ä¸æåææ¬å¹¶è¿åä¸ä¸ªæ°çå符串ã对å®ä»¬ä¸çä¸ä¸ªçææ¬è¿è¡çæ´æ¹ä¸ä¼å½±åå¦ä¸ä¸ªå符串ã
slice() æ¹æ³æåç´å°ä½ä¸å
æ¬ indexEnd çææ¬ãä¾å¦ï¼str.slice(1, 4) æåçæ¯ç¬¬äºä¸ªå符å°ç¬¬å个å符ï¼å符çç´¢å¼ä¸º 1ã2 å 3ï¼ã
- 妿
indexStart >= str.lengthï¼åè¿åä¸ä¸ªç©ºå符串ã - 妿
indexStart < 0ï¼åç´¢å¼ä»å符串æ«å°¾å¼å§è®¡æ°ãæ´æ£å¼å°è¯´ï¼å¨è¿ç§æ åµä¸ï¼åå符串ä»max(indexStart + str.length, 0)å¼å§ã - 妿
indexStart被çç¥ã为 undefinedï¼ææ æ³è½¬æ¢ä¸ºæ°åï¼ä½¿ç¨Number(indexStart)ï¼ï¼åå°å ¶è§ä¸º0ã - 妿
indexEnd被çç¥ã为 undefinedï¼ææ æ³è½¬æ¢ä¸ºæ°åï¼ä½¿ç¨Number(indexEnd)ï¼ï¼æèindexEnd >= str.lengthï¼åslice()æåå°åç¬¦ä¸²çæ«å°¾ã - 妿
indexEnd < 0ï¼åç´¢å¼ä»å符串æ«å°¾å¼å§è®¡æ°ãæ´æ£å¼å°è¯´ï¼å¨è¿ç§æ åµä¸ï¼åå符串å¨max(indexEnd + str.length, 0)å¤ç»æã - 卿 ååè´å¼åï¼å¦æ
indexEnd <= indexStartï¼å³indexEnd表示ä½äºindexStartä¹åçå符ï¼ï¼åè¿åä¸ä¸ªç©ºå符串ã
示ä¾
>ä½¿ç¨ slice() å建ä¸ä¸ªæ°çå符串
以ä¸ç¤ºä¾ä½¿ç¨ slice() å建äºä¸ä¸ªæ°å符串ã
const str1 = "The morning is upon us."; // str1 çé¿åº¦æ¯ 23ã
const str2 = str1.slice(1, 8);
const str3 = str1.slice(4, -2);
const str4 = str1.slice(12);
const 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); // ""
使ç¨è´å¼ç´¢å¼è°ç¨ slice()
ä¸é¢çä¾åå¨ä½¿ç¨ slice() æ¶ä¼ å
¥äºè´å¼ä½ä¸ºç´¢å¼ã
const str = "The morning is upon us.";
str.slice(-3); // 'us.'
str.slice(-3, -1); // 'us'
str.slice(0, -1); // 'The morning is upon us'
str.slice(4, -1); // 'morning is upon us'
è¿ä¸ªä¾åéè¿ä»å符串æ«å°¾åæ° 11 个åç¬¦æ¥æ¾å°èµ·å§ç´¢å¼ï¼å¹¶éè¿ä»å符串å¼å¤´æ£æ° 16 个åç¬¦æ¥æ¾å°ç»æç´¢å¼ã
console.log(str.slice(-11, 16)); // "is u"
å¨è¿ä¸ªä¾åä¸ï¼å®éè¿ä»å符串å¼å¤´æ£æ° 11 个åç¬¦æ¥æ¾å°èµ·å§ç´¢å¼ï¼å¹¶éè¿ä»å符串æ«å°¾åæ° 7 个åç¬¦æ¥æ¾å°ç»æç´¢å¼ã
console.log(str.slice(11, -7)); // " is u"
è¿äºåæ°éè¿ä»å符串æ«å°¾åæ° 5 个åç¬¦æ¥æ¾å°èµ·å§ç´¢å¼ï¼å¹¶éè¿ä»å符串æ«å°¾åæ° 1 个åç¬¦æ¥æ¾å°ç»æç´¢å¼ã
console.log(str.slice(-5, -1)); // "n us"
è§è
| è§è |
|---|
| ECMAScript® 2027 Language Specification> # sec-string.prototype.slice> |