string.slice
slice() ๋ฉ์๋๋ ๋ฌธ์์ด์ ์น์
์ ์ถ์ถํ์ฌ ์๋ ๋ฌธ์์ด์ ์์ ํ์ง ์๊ณ ์ ๋ฌธ์์ด์ ๋ฆฌํดํ๋ค.
const str = 'The cat (Felis catus) is a domestic species of small carnivorous mammal.';
str.slice(31); // "stic species of small carnivorous mammal."
str.slice(4, 19); // "cat (Felis catu"
str.slice(-4); // "mal."
str.slice(-9, -5); // "s ma"Syntax
str.slice(beginIndex[, endIndex]);Parameters
beginIndex
์ถ์ถ์ ์์ํ ์ธ๋ฑ์ค(0๋ถํฐ ์์)์ด๋ค. ๋ง์ฝ ์์์ด๋ฉด str.length + beginIndex๋ก ์ทจ๊ธํ๋ค. (์๋ฅผ ๋๋ฉด -3์ด๋ฉด str.length + - 3 ์ด๋ค)
beginIndex๊ฐ str.length์ ๊ฐ๊ฑฐ๋ ํฌ๋ฉด slice()๋ ๋น ๋ฌธ์์ด์ ๋ฐํํ๋ค.
endIndex (Optional)
์ถ์ถ์ ๋๋ด๋ 0๋ถํฐ ์์ํ๋ index, ์ด index์ ๋ฌธ์๋ ํฌํจ๋์ง ์๋๋ค. ๋ง์ฝ endIndex๊ฐ ์๋ต๋๋ค๋ฉด, slice()๋ ๋ฌธ์์ด ๋ง์ง๋ง๊น์ง ์ถ์ถํ๋ค. ๋ง์ฝ ์์๋ผ๋ฉด, endIndex๋ str.length + endIndex๋ก ์ทจ๊ธํ๋ค. (์๋ฅผ ๋ค๋ฉด endIndex๊ฐ -3์ด๋ฉด ์์์ ์ str.length - 3)
Return value
๋ฌธ์์ด์ ์น์ ์ ์ถ์ถํ ์๋ก์ด ๋ฌธ์์ด
Description
slice()๋ ํ ๋ฌธ์์ด์์ ํ
์คํธ๋ฅผ ์ถ์ถํ์ฌ ์ ๋ฌธ์์ด์ ๋ฐํํ๋ค. ํ ๋ฌธ์์ด์ ํ
์คํธ๋ฅผ ๋ณ๊ฒฝํด๋ ๋ค๋ฅธ ๋ฌธ์์ด์๋ ์ํฅ์ ๋ฏธ์น์ง ์๋๋ค. slice() ๋ endIndex ๋ฅผ ํฌํจํ์ง ์๋๋ค. str.slice(1, 4) ๋ ๋๋ฒ์งธ ๋ฌธ์๋ถํฐ ๋ค๋ฒ์งธ ๋ฌธ์๊น์ง ์ถ์ถํ๋ค. (1, 2, 3 ์ธ๋ฑ์ค ๋ฌธ์).
str.slice(2, -1) ์ธ ๋ฒ์งธ ๋ฌธ์๋ถํฐ ๋ฌธ์์ด์ ๋ง์ง๋ง์์ ๋๋ฒ์งธ ๋ฌธ์๊น์ง ์ถ์ถํ๋ค.
Examples
slice()๋ฅผ ์ด์ฉํ์ฌ ์๋ก์ด ๋ฌธ์์ด ๋ง๋ค๊ธฐ
let str1 = 'Cats are common pets throughout the world, and their worldwide population exceeds 500 million as of 2007.',
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);
str2; // "ats are"
str3; // " are common pets throughout the world, and their worldwide population exceeds 500 million as of 200"
str4; // "mon pets throughout the world, and their worldwide population exceeds 500 million as of 2007."
str5; // "t the world, and their worldwide population exceeds 500 million as of 2007."์์ ์ธ๋ฑ์ค๋ก slice() ์ฌ์ฉํ๊ธฐ
let str = 'Cats are common pets throughout the world';
str.slice(-1); // "d" str.length-1 ๋ถํฐ ๋๊น์ง์ด๋ค.
str.slice(-1, -1); // ""
str.slice(-3); // "rld" str.length - 3 ๋ถํฐ ๋๊น์ง์ด๋ค.
str.slice(-3, -1); // "rl" str.length - 3 ๋ถํฐ str.length - 1์ ํฌํจํ์ง ์์
str.slice(0, -1); // "Cats are common pets throughout the worl" 0๋ถํฐ str.length - 1์ ํฌํจํ์ง ์์str.slice(-11, 33); // "t t"beginIndex๋ str.length - 11 ๋ถํฐ์ธ 30์ด๊ณ endIndex๋ 33์ด๋ฉฐ ํฌํจํ์ง ์์ ๊ทธ ์๊น์ง์ด๋ค. (30, 31, 32)
str.slice(30, -8); // "t t"beginIndex๋ 33๋ถํฐ, endIndex๋ str.length - 8 ์ธ 33์ด๋ฉฐ ํฌํจ๋์ง ์์ ๊ทธ ์๊น์ง์ด๋ค. (30, 31, 32)
str.slice(-5, -1); // "worl"beginIndex๋ str.length - 5 ์ธ 36๋ถํฐ์ด๊ณ , endIndex๋ str.length - 1์ธ 40์ด๊ณ ํฌํจํ์ง ์์ ๊ทธ ์๊น์ง์ด๋ค. (36, 37, 38, 39)
Last updated
Was this helpful?