Bibi's DevLog ๐Ÿค“๐ŸŽ

[Javascript] .split(), join()์„ ํ™œ์šฉํ•ด ๋ฌธ์ž์—ด์„ ์—ฌ๋Ÿฌ ์กฐ๊ฑด์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/Javascript ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

[Javascript] .split(), join()์„ ํ™œ์šฉํ•ด ๋ฌธ์ž์—ด์„ ์—ฌ๋Ÿฌ ์กฐ๊ฑด์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ

๋น„๋น„ bibi 2020. 10. 28. 14:45

.split()๊ณผ .join()์„ ๋ฐ˜๋ณต์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

๋ฌธ์ž์—ด.split()
: ์†Œ๊ด„ํ˜ธ ๋‚ด์˜ ๊ธฐํ˜ธ๋กœ ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ„์–ด ๋ฐฐ์—ด๋กœ ๋งŒ๋“ฆ

๋ฐฐ์—ด.join()
: ์†Œ๊ด„ํ˜ธ ๋‚ด์˜ ๊ธฐํ˜ธ๋กœ ๋ฐฐ์—ด์˜ ๊ฐ ์›์†Œ๋ฅผ ์ด์–ด๋ถ™์—ฌ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ฆ

ํ•œ ๋งˆ๋””๋กœ .split()์€ ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋‚˜๋ˆ„๊ณ , .join()์€ ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ ์ด์–ด๋ถ™์ธ๋‹ค.

์•„๋ž˜์™€ ๊ฐ™์ด ํ™œ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค.

Q1. "a=b,c:d" ๋ผ๋Š” ๋ฌธ์ž์—ด str์„ = , : ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆ„์–ด ["a", "b", "c", "d"]๋ผ๋Š” ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค๊ณ  ์‹ถ๋‹ค.

var str = "a=b,c:d";
str; // "a=b,c:d"
str.split("=");
// (2) ["a", "b,c:d"]
str;
// "a=b,c:d". str์€ ๊ทธ๋Œ€๋กœ์ด๋‹ค.

str.split("=").join(",");
// "a,b,c:d"
str.split("=").join(",").split(":");
// (2) ["a,b,c", "d"]
str.split("=").join(",").split(":").join(",");
// "a,b,c,d"
str.split("=").join(",").split(":").join(",").split(",");
// (4) ["a", "b", "c", "d"]

์ฆ‰ split()์œผ๋กœ ์›ํ•˜๋Š” ์กฐ๊ฑด(= , : )์˜ ๊ธฐํ˜ธ๋ฅผ ํ•˜๋‚˜ํ•˜๋‚˜ ๋นผ์„œ ๋ฐฐ์—ด๋กœ ๋‚˜๋ˆ„๊ณ ,
๋‚˜๋ˆ ์ง„ ๋ฐฐ์—ด์„ join(",")์œผ๋กœ ๋‹ค์‹œ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

Q2. "10+2/3-1*5" ๋ผ๋Š” ๋ฌธ์ž์—ด์˜ ์ˆซ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ["10", "2", "3", "1", "5"]๋ผ๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ  ์‹ถ๋‹ค.

var input = "10+2/3-1*5";
input.split("+");
// (2) ["10", "2/3-1*5"]
input.split("+").join(",");
// "10,2/3-1*5"
input.split("+").join(",").split("*");
// (2) ["10,2/3-1", "5"]
input.split("+").join(",").split("*").join(",");
// "10,2/3-1,5"
input.split("+").join(",").split("*").join(",").split("/");
// (2) ["10,2", "3-1,5"]
input.split("+").join(",").split("*").join(",").split("/").join(",");
// "10,2,3-1,5"
input.split("+").join(",").split("*").join(",").split("/").join(",").split("-");
// (2) ["10,2,3", "1,5"]
input.split("+").join(",").split("*").join(",").split("/").join(",").split("-").join(",");
// "10,2,3,1,5"
input.split("+").join(",").split("*").join(",").split("/").join(",").split("-").join(",").split(",")
// (5) ["10", "2", "3", "1", "5"]

.split()๊ณผ .join()์„ ๋ฐ˜๋ณต์ ์œผ๋กœ ์จ์•ผ ํ•ด์„œ ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๋Š” ๋ถˆํŽธํ•จ์ด ์žˆ์ง€๋งŒ 
์ง€๊ธˆ์˜ ๋‚ด ์ˆ˜์ค€(์ดˆ๋ณด)์œผ๋กœ์„  ๊ฐ€์žฅ ํ™•์‹คํ•˜๊ณ  ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

๊ทธ ์™ธ .split() ์†Œ๊ด„ํ˜ธ ๋‚ด์— ์ •๊ทœํ‘œํ˜„์‹์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค๊ณ .

์ฐธ๊ณ  : lottogame.tistory.com/678

 

์ž๋ฐ” ์Šคํฌ๋ฆฝํŠธ์—์„œ ๋ฌธ์ž์—ด์„ ์—ฌ๋Ÿฌ ๊ตฌ๋ถ„ ๊ธฐํ˜ธ๋กœ ๋ถ„๋ฆฌํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒํ•ฉ๋‹ˆ๊นŒ?

์ž๋ฐ” ์Šคํฌ๋ฆฝํŠธ์—์„œ ๋ฌธ์ž์—ด์„ ์—ฌ๋Ÿฌ ๊ตฌ๋ถ„ ๊ธฐํ˜ธ๋กœ ๋ถ„๋ฆฌํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒํ•ฉ๋‹ˆ๊นŒ? JavaScript์—์„œ ๋ฌธ์ž์—ด์„ ์—ฌ๋Ÿฌ ๊ตฌ๋ถ„ ๊ธฐํ˜ธ๋กœ ๋ถ„๋ฆฌํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒํ•ฉ๋‹ˆ๊นŒ? ์‰ผํ‘œ์™€ ๊ณต๋ฐฑ์œผ๋กœ ๋ถ„ํ• ํ•˜๋ ค๊ณ ํ•˜์ง€๋งŒ JS์˜ ๋ถ„ํ•  ๊ธฐ๋Šฅ

lottogame.tistory.com