๐Ÿ”—
โ† ๊ฐ€์ด๋“œ ๋ชฉ๋ก์œผ๋กœ

JavaScript์—์„œ URL ์ธ์ฝ”๋”ฉ โ€” encodeURI, encodeURIComponent ๋ฐ ๋ชจ๋ฒ” ์‚ฌ๋ก€

ยท ํƒœ๊ทธ: javascript, url-encoding, encodeURIComponent, encodeURI, programming

JavaScript๋Š” URL ์ธ์ฝ”๋”ฉ์„ ์œ„ํ•œ ๋‘ ๊ฐ€์ง€ ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค:

encodeURIComponent()

๋‹ค์Œ ๋ฌธ์ž๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ์ธ์ฝ”๋”ฉํ•ฉ๋‹ˆ๋‹ค: A-Z a-z 0-9 - _ . ! ~ * ' ( )

const name = 'John Doe'
const query = '?name=' + encodeURIComponent(name)
// ?name=John%20Doe

๊ฐœ๋ณ„ ์ฟผ๋ฆฌ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ’, ๊ฒฝ๋กœ ์„ธ๊ทธ๋จผํŠธ ๋˜๋Š” URL์˜ ์ผ๋ถ€๊ฐ€ ๋˜๋Š” ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ์ธ์ฝ”๋”ฉํ•  ๋•Œ ์‚ฌ์šฉํ•˜์„ธ์š”.

encodeURI()

์œ„์˜ ๋ฌธ์ž ์™ธ์—๋„ ์˜ˆ์•ฝ๋œ URL ๋ฌธ์ž๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ๋ฌธ์ž๋ฅผ ์ธ์ฝ”๋”ฉํ•ฉ๋‹ˆ๋‹ค: : / ? # [ ] @ ! $ & ' ( ) * + , ; =

const url = 'https://example.com/search?q=hello world'
const encoded = encodeURI(url)
// https://example.com/search?q=hello%20world

์™„์ „ํ•œ URL ๋ฌธ์ž์—ด์„ ์ธ์ฝ”๋”ฉํ•  ๋•Œ ์‚ฌ์šฉํ•˜์„ธ์š”.

์ผ๋ฐ˜์ ์ธ ํ•จ์ •

// ์ž˜๋ชป๋œ ๋ฐฉ๋ฒ• โ€” URL ๊ตฌ์กฐ๊ฐ€ ๊นจ์ง‘๋‹ˆ๋‹ค
encodeURIComponent('https://example.com/page')
// https%3A%2F%2Fexample.com%2Fpage

// ์˜ฌ๋ฐ”๋ฅธ ๋ฐฉ๋ฒ• โ€” ๊ตฌ์กฐ๊ฐ€ ๋ณด์กด๋ฉ๋‹ˆ๋‹ค
encodeURI('https://example.com/page')
// https://example.com/page

์ €ํฌ URL ์ธ์ฝ”๋”/๋””์ฝ”๋” ๋„๊ตฌ์—์„œ ์ด ํ•จ์ˆ˜๋“ค์„ ์‹ค์‹œ๊ฐ„์œผ๋กœ ํ…Œ์ŠคํŠธํ•ด ๋ณด์„ธ์š”.

JavaScript์—์„œ URL ์ธ์ฝ”๋”ฉ โ€” encodeURI, encodeURIComponent ๋ฐ ๋ชจ๋ฒ” ์‚ฌ๋ก€ - CoolTool