โ ๊ฐ์ด๋ ๋ชฉ๋ก์ผ๋ก
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 ์ธ์ฝ๋/๋์ฝ๋ ๋๊ตฌ์์ ์ด ํจ์๋ค์ ์ค์๊ฐ์ผ๋ก ํ ์คํธํด ๋ณด์ธ์.