ToolDeck

URL Encode JavaScript — encodeURIComponent()

·Front-end & Node.js Developer·ตรวจสอบโดยSophie Laurent·เผยแพร่เมื่อ

ใช้ เข้ารหัส URL ออนไลน์ ฟรีโดยตรงในเบราว์เซอร์ของคุณ — ไม่ต้องติดตั้ง

ลอง เข้ารหัส URL ออนไลน์ ออนไลน์ →

เมื่อคุณสร้าง URL ค้นหา ส่งเส้นทาง redirect เป็นพารามิเตอร์ query หรือสร้างคำขอการอนุญาต OAuth ตัวอักษรพิเศษอย่าง &, = และช่องว่างจะทำให้ URL เสียหายอย่างเงียบๆ หากคุณไม่เข้ารหัส URL ก่อน JavaScript มีสามวิธีที่ built-in — encodeURIComponent(), encodeURI() และ URLSearchParams — แต่ละอันออกแบบมาสำหรับกรณีใช้งานที่แตกต่างกัน และการเลือกผิดคือสาเหตุหลักของ bug การเข้ารหัสส่วนใหญ่ที่พบในการ code review สำหรับการเข้ารหัสด่วนโดยไม่ต้องเขียน code, ตัวเข้ารหัส URL ของ ToolDeck จัดการได้ทันทีในเบราว์เซอร์ คู่มือนี้ครอบคลุมทั้งสามวิธีอย่างละเอียด (JavaScript ES2015+ / Node.js 10+): ควรใช้แต่ละอันเมื่อใด ความแตกต่างสำหรับช่องว่างและ ตัวอักษรพิเศษ รูปแบบ Fetch และ API ในโลกจริง การใช้งาน CLI และสี่ข้อผิดพลาดที่ทำให้เกิด bug ใน production ที่ละเอียดอ่อนที่สุด

  • encodeURIComponent() คือตัวเลือกที่ถูกต้องสำหรับการเข้ารหัสค่าพารามิเตอร์แต่ละตัว — โดยจะเข้ารหัสทุกตัวอักษรยกเว้น A–Z, a–z, 0–9 และ - _ . ! ~ * ' ( )
  • encodeURI() เข้ารหัส URL ทั้งหมดพร้อมกับรักษาตัวอักษรโครงสร้าง (/ ? # & = :) ไว้ — ไม่ควรใช้กับค่าแต่ละตัว
  • URLSearchParams เข้ารหัสคู่ key-value โดยอัตโนมัติโดยใช้รูปแบบ application/x-www-form-urlencoded ซึ่งช่องว่างจะกลายเป็น + แทน %20
  • Double-encoding เป็น bug ใน production ที่พบบ่อยที่สุด: encodeURIComponent(encodeURIComponent(value)) จะเปลี่ยน %20 เป็น %2520
  • ไลบรารี qs จัดการ nested objects และ arrays ใน query string ได้โดยตรง — URLSearchParams มาตรฐานไม่รองรับสิ่งนี้

URL Encoding คืออะไร?

URL encoding (เรียกอย่างเป็นทางการว่า percent-encoding ซึ่งกำหนดไว้ใน RFC 3986) แปลงตัวอักษรที่ไม่ได้รับอนุญาตหรือมีความหมายพิเศษใน URL ให้เป็นการแทนที่ปลอดภัย ไบต์ที่ไม่ปลอดภัยแต่ละตัวจะถูกแทนที่ด้วยเครื่องหมายเปอร์เซ็นต์ตามด้วยเลขฐานสิบหก สองตัว — คือรหัส ASCII ของตัวอักษรนั้น ช่องว่างกลายเป็น %20 เครื่องหมาย & กลายเป็น %26 เครื่องหมาย / กลายเป็น %2F

ตัวอักษรที่ปลอดภัยเสมอและไม่เคยถูกเข้ารหัสเรียกว่า ตัวอักษรที่ไม่ถูกสงวนไว้: ตัวอักษร A–Z และ a–z ตัวเลข 0–9 และสัญลักษณ์สี่ตัว - _ . ~ ส่วนที่เหลือทั้งหมดต้องถูกเข้ารหัส เมื่อใช้เป็นข้อมูล หรือมีบทบาทเชิงโครงสร้างใน URL (เช่น / คั่นส่วนของ path หรือ &คั่นพารามิเตอร์ query) ผลที่ตามมาในทางปฏิบัติ: ชื่อสินค้าอย่าง “Keyboard & Mouse ไร้สาย” ใน พารามิเตอร์ query จะทำลายโครงสร้าง URL หากส่งแบบดิบ

Before · text
After · text
https://shop.example.com/search?q=Wireless Keyboard & Mouse&category=peripherals
https://shop.example.com/search?q=Wireless%20Keyboard%20%26%20Mouse&category=peripherals

encodeURIComponent() — ฟังก์ชันที่ถูกต้องสำหรับ Query Parameters

encodeURIComponent() คือกำลังหลักของ URL encoding ใน JavaScript ฟังก์ชันนี้เข้ารหัสทุกตัวอักษร ยกเว้น ชุดที่ไม่ถูกสงวน (A–Z, a–z, 0–9, - _ . ! ~ * ' ( )) ที่สำคัญคือ ฟังก์ชันนี้เข้ารหัสตัวอักษรทั้งหมดที่มีความหมายเชิงโครงสร้างใน URL — &, =, ?, #, / — ซึ่งทำให้ปลอดภัยสำหรับใช้ในค่าพารามิเตอร์ ไม่จำเป็นต้อง import; ฟังก์ชันนี้เป็น global function ที่มีอยู่ในทุก JavaScript environment

ตัวอย่างขั้นต่ำที่ใช้งานได้

JavaScript (browser / Node.js)
// Encode a search query parameter that contains special characters
const searchQuery  = 'Wireless Keyboard & Mouse'
const filterStatus = 'in-stock'
const maxPrice     = '149.99'

const searchUrl = `https://shop.example.com/products?` +
  `q=${encodeURIComponent(searchQuery)}` +
  `&status=${encodeURIComponent(filterStatus)}` +
  `&maxPrice=${encodeURIComponent(maxPrice)}`

console.log(searchUrl)
// https://shop.example.com/products?q=Wireless%20Keyboard%20%26%20Mouse&status=in-stock&maxPrice=149.99

การเข้ารหัส URL redirect เป็น query parameter

JavaScript
// The redirect destination is itself a URL — it must be fully encoded
// or the outer URL parser will misinterpret its ? and & as its own
const redirectAfterLogin = 'https://dashboard.internal/reports?view=weekly&team=platform'

const loginUrl = `https://auth.company.com/login?next=${encodeURIComponent(redirectAfterLogin)}`

console.log(loginUrl)
// https://auth.company.com/login?next=https%3A%2F%2Fdashboard.internal%2Freports%3Fview%3Dweekly%26team%3Dplatform

// Decoding on the receiving end
const params    = new URLSearchParams(window.location.search)
const next      = params.get('next')              // Automatically decoded
const nextUrl   = new URL(next!)                  // Safe to parse
console.log(nextUrl.hostname)                     // dashboard.internal

การเข้ารหัสตัวอักษร non-ASCII และ Unicode

JavaScript
// encodeURIComponent handles Unicode natively in all modern environments
// Each UTF-8 byte of the character is percent-encoded
const customerName = 'สมชาย ใจดี'
const productTitle = '東京 wireless adapter'
const reviewText   = 'ดีมาก — ทำงานได้อย่างสมบูรณ์'

console.log(encodeURIComponent(customerName))
// %E0%B8%AA%E0%B8%A1%E0%B8%8A%E0%B8%B2%E0%B8%A2%20%E0%B9%83%E0%B8%88%E0%B8%94%E0%B8%B5

console.log(encodeURIComponent(productTitle))
// %E6%9D%B1%E4%BA%AC%20wireless%20adapter

console.log(encodeURIComponent(reviewText))
// %E0%B8%94%E0%B8%B5%E0%B8%A1%E0%B8%B2%E0%B8%81%20%E2%80%94%20...

// Decoding back
console.log(decodeURIComponent('%E0%B8%AA%E0%B8%A1%E0%B8%8A%E0%B8%B2%E0%B8%A2%20%E0%B9%83%E0%B8%88%E0%B8%94%E0%B8%B5'))
// สมชาย ใจดี
หมายเหตุ:encodeURIComponent() ใช้การเข้ารหัส string UTF-16 ภายในของ JavaScript engine จากนั้นเข้ารหัสแต่ละ byte UTF-8 ของตัวอักษรแยกกัน ตัวอักษรอย่าง ü (U+00FC) เข้ารหัสเป็น %C3%BC เพราะการแทนค่า UTF-8 คือสอง byte: 0xC3 และ 0xBC นี่คือสิ่งที่ถูกต้องและเป็นไปตามมาตรฐาน URI — server คาดว่าจะถอดรหัสลำดับ byte UTF-8 กลับเป็น codepoint ต้นฉบับ

ฟังก์ชัน URL Encoding ของ JavaScript — อ้างอิงตัวอักษร

วิธีการเข้ารหัส native ทั้งสามแตกต่างกันในตัวอักษรที่เข้ารหัส ตารางด้านล่างแสดง output สำหรับตัวอักษรที่มักก่อปัญหามากที่สุด:

ตัวอักษรบทบาทใน URLencodeURIComponent()encodeURI()URLSearchParams
ช่องว่างคั่นคำ%20%20+
&คั่น parameter%26คงไว้%26
=key=value%3Dคงไว้%3D
+ช่องว่างที่เข้ารหัส (form)%2B%2B%2B
?เริ่มต้น query%3Fคงไว้%3F
#fragment%23คงไว้%23
/คั่น path%2Fคงไว้%2F
:scheme / port%3Aคงไว้%3A
@คั่น auth%40คงไว้%40
%ตัวอักษร percent%25%25%25
~ไม่ถูกสงวนคงไว้คงไว้คงไว้

คอลัมน์สำคัญคือ encodeURIComponent() กับ encodeURI() สำหรับ & และ =: encodeURI() ปล่อยให้ไม่เปลี่ยนแปลง ซึ่งถูกต้องเมื่อเข้ารหัส URL ทั้งหมด แต่หายนะเมื่อเข้ารหัสค่าที่มีตัวอักษรเหล่านี้

encodeURI() — เมื่อต้องการรักษาโครงสร้าง URL

encodeURI() ออกแบบมาสำหรับการเข้ารหัส URL ทั้งหมด— จะรักษาตัวอักษรทั้งหมดที่เป็นส่วนโครงสร้างที่ถูกต้องของ URI: scheme (https://), host, ตัวคั่น path, ตัวคั่น query และตัวระบุ fragment ใช้เมื่อคุณได้รับ URL ที่อาจมีช่องว่างหรือตัวอักษร non-ASCII ในส่วน path แต่คุณต้องการรักษาโครงสร้างไว้

การทำความสะอาด URL ที่ผู้ใช้ให้มา

JavaScript
// A URL pasted from a document with spaces in the path and non-ASCII chars
const rawUrl = 'https://cdn.example.com/assets/product images/München chair.png'

const safeUrl = encodeURI(rawUrl)
console.log(safeUrl)
// https://cdn.example.com/assets/product%20images/M%C3%BCnchen%20chair.png

// encodeURIComponent would break it — it encodes the :// and all / characters
const broken = encodeURIComponent(rawUrl)
console.log(broken)
// https%3A%2F%2Fcdn.example.com%2Fassets%2Fproduct%20images%2FM%C3%BCnchen%20chair.png
// ↑ Not a valid URL — the scheme and slashes are destroyed
หมายเหตุ:Constructor URL มักเป็นตัวเลือกที่ดีกว่า encodeURI() สำหรับการจัดการ string URL ที่ผู้ใช้ให้มา — ฟังก์ชันนี้ทำให้ URL เป็นรูปแบบมาตรฐาน ตรวจสอบโครงสร้าง และให้ API ที่ชัดเจนสำหรับเข้าถึง แต่ละองค์ประกอบ สำรอง encodeURI() ไว้สำหรับกรณีที่คุณต้องการ ผลลัพธ์เป็น string และรู้แล้วว่า input มีโครงสร้างที่ถูกต้องตาม URL

URLSearchParams — วิธีทันสมัยสำหรับ Query Strings

URLSearchParams คือวิธีเฉพาะภาษาในการสร้างและ parse query strings ใน JavaScript ยุคใหม่ มีให้ใช้ globally ในทุกเบราว์เซอร์ยุคใหม่ และ Node.js 10+ และจัดการการเข้ารหัสโดยอัตโนมัติ — คุณทำงานกับคู่ key-value ธรรมดา และมันจะสร้าง output ที่ถูกต้อง รายละเอียดสำคัญหนึ่งอย่าง: ฟังก์ชันนี้ปฏิบัติตาม specification application/x-www-form-urlencodedซึ่งเข้ารหัสช่องว่างเป็น + แทน %20 นี่คือสิ่งที่ถูกต้องและได้รับการรองรับ อย่างกว้างขวาง แต่ควรตระหนักเมื่อ server ของคุณต้องการรูปแบบเฉพาะ

การสร้าง URL คำขอค้นหา

JavaScript (browser / Node.js 10+)
// Building a search API URL with multiple parameters
const filters = {
  query:    'standing desk',
  category: 'office-furniture',
  minPrice: '200',
  maxPrice: '800',
  inStock:  'true',
  sortBy:   'price_asc',
}

const params = new URLSearchParams(filters)

const apiUrl = `https://api.example.com/v2/products?${params}`
console.log(apiUrl)
// https://api.example.com/v2/products?query=standing+desk&category=office-furniture&minPrice=200&maxPrice=800&inStock=true&sortBy=price_asc

// Appending additional params after construction
params.append('page', '2')
params.append('tag', 'ergonomic & adjustable')
console.log(params.toString())
// query=standing+desk&...&tag=ergonomic+%26+adjustable

การ parse query string ที่เข้ามา

JavaScript
// Both browser (window.location.search) and Node.js (req.url) scenarios
function parseWebhookCallbackUrl(rawSearch: string) {
  const params = new URLSearchParams(rawSearch)

  return {
    eventId:     params.get('event_id'),       // null if missing
    timestamp:   Number(params.get('ts')),
    signature:   params.get('sig'),
    redirectUrl: params.get('redirect'),       // Automatically decoded
    tags:        params.getAll('tag'),         // Handles repeated keys
  }
}

const callbackQuery = '?event_id=evt_9c2f&ts=1717200000&sig=sha256%3Dabc123&redirect=https%3A%2F%2Fdashboard.internal%2F&tag=payment&tag=webhook'

const parsed = parseWebhookCallbackUrl(callbackQuery)
console.log(parsed.redirectUrl)  // https://dashboard.internal/
console.log(parsed.tags)         // ['payment', 'webhook']

วิธีเข้ารหัส Parameters ใน JavaScript Fetch Requests

สถานที่ทั่วไปที่สุดที่ URL encoding ปรากฏใน production code คือภายในการเรียก fetch() — ไม่ว่าจะเป็นการสร้าง URL ของคำขอ หรือการส่งข้อมูล form ใน request body แต่ละสถานการณ์มีวิธีที่ถูกต้องของตัวเอง

GET request — การเข้ารหัส query parameters

JavaScript (browser / Node.js 18+)
async function searchInventory(params: {
  sku?:      string
  warehouse: string
  minStock:  number
  updatedAfter?: Date
}): Promise<{ items: unknown[]; total: number }> {
  const searchParams = new URLSearchParams()

  if (params.sku)          searchParams.set('sku',          params.sku)
  searchParams.set('warehouse',  params.warehouse)
  searchParams.set('min_stock',  String(params.minStock))
  if (params.updatedAfter) searchParams.set('updated_after', params.updatedAfter.toISOString())

  const url = `https://inventory.internal/api/items?${searchParams}`

  const res = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${process.env.INVENTORY_API_KEY}`,
      'Accept':        'application/json',
    },
  })

  if (!res.ok) {
    throw new Error(`Inventory API ${res.status}: ${await res.text()}`)
  }

  return res.json()
}

const results = await searchInventory({
  warehouse:    'eu-west-1',
  minStock:     10,
  updatedAfter: new Date('2025-01-01'),
})

console.log(`Found ${results.total} items`)

POST request — URL-encoding form body

JavaScript
// application/x-www-form-urlencoded POST — used by OAuth token endpoints,
// legacy form-submission APIs, and some webhook providers
async function requestOAuthToken(
  clientId:     string,
  clientSecret: string,
  code:         string,
  redirectUri:  string,
): Promise<{ access_token: string; expires_in: number }> {
  const body = new URLSearchParams({
    grant_type:    'authorization_code',
    client_id:     clientId,
    client_secret: clientSecret,
    code,
    redirect_uri:  redirectUri,  // URLSearchParams encodes this automatically
  })

  const res = await fetch('https://oauth.provider.com/token', {
    method:  'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body:    body.toString(),
    // body: body — also works directly in modern environments (Fetch spec accepts URLSearchParams)
  })

  if (!res.ok) {
    const err = await res.json()
    throw new Error(`OAuth error: ${err.error_description ?? err.error}`)
  }

  return res.json()
}

เมื่อคุณต้องการทดสอบหรือ debug URL ที่เข้ารหัสแล้วโดยไม่ต้องตั้งค่า script ให้วาง ค่า raw ลงใน ตัวเข้ารหัส URL โดยตรง — ฟังก์ชันนี้เข้ารหัสและถอดรหัสทันที แสดงให้เห็นว่าเบราว์เซอร์และ server จะเห็นอะไร มีประโยชน์สำหรับการตรวจสอบ OAuth redirect URI, URL callback webhook และ parameters ของ CDN signed request

URL Encoding ผ่าน Command Line ด้วย Node.js และ Shell

สำหรับ shell scripts, CI pipelines หรือการ debug เร็ว วิธีการ command line หลายอย่าง ทำงานได้โดยไม่ต้องเขียน script เต็มรูปแบบ

bash
# ── Node.js one-liners — cross-platform (macOS, Linux, Windows) ────────

# encodeURIComponent — encode a single value
node -e "console.log(encodeURIComponent(process.argv[1]))" "Wireless Keyboard & Mouse"
# Wireless%20Keyboard%20%26%20Mouse

# Build a complete query string
node -e "console.log(new URLSearchParams(JSON.parse(process.argv[1])).toString())"   '{"q":"standing desk","category":"office-furniture","page":"1"}'
# q=standing+desk&category=office-furniture&page=1

# Decode a percent-encoded string
node -e "console.log(decodeURIComponent(process.argv[1]))" "Wireless%20Keyboard%20%26%20Mouse"
# Wireless Keyboard & Mouse

# ── curl — automatic encoding ───────────────────────────────────────────
# curl --data-urlencode encodes values automatically in GET and POST
curl -G "https://api.example.com/search"   --data-urlencode "q=Wireless Keyboard & Mouse"   --data-urlencode "category=office furniture"

# ── Python one-liner (available on most systems) ─────────────────────────
python3 -c "from urllib.parse import quote; print(quote(input(), safe=''))"
# (type the string and press Enter)

# ── jq + bash: encode every value in a JSON object ───────────────────────
echo '{"q":"hello world","tag":"node & express"}' |   node -e "const d=JSON.parse(require('fs').readFileSync('/dev/stdin','utf8'));            console.log(new URLSearchParams(d).toString())"
# q=hello+world&tag=node+%26+express

ทางเลือกประสิทธิภาพสูง: qs

URLSearchParams ที่ built-in ไม่รองรับ nested objects หรือ arrays — รูปแบบ query strings ที่ใช้โดย API และ framework หลายตัว ไลบรารี qs (ดาวน์โหลด npm 30M+ ต่อสัปดาห์) จัดการรูปแบบ query string ที่ใช้ในโลกจริงได้ครบถ้วน: nested objects ด้วย bracket notation (filters[status]=active), repeated keys, custom encoders และรูปแบบ array serialisation ที่กำหนดค่าได้

bash
npm install qs
# or
pnpm add qs
JavaScript
import qs from 'qs'

// URLSearchParams cannot represent this structure natively
const reportFilters = {
  dateRange: {
    from: '2025-01-01',
    to:   '2025-03-31',
  },
  status:    ['published', 'archived'],
  author:    { id: 'usr_4f2a9c1b', role: 'editor' },
  workspace: 'ws-platform-eu',
}

// qs produces bracket-notation query strings used by Express, Rails, Django REST
const query = qs.stringify(reportFilters, { encode: true })
console.log(query)
// dateRange%5Bfrom%5D=2025-01-01&dateRange%5Bto%5D=2025-03-31&status%5B0%5D=published&status%5B1%5D=archived&author%5Bid%5D=usr_4f2a9c1b&author%5Brole%5D=editor&workspace=ws-platform-eu

// Human-readable (no encoding) — useful for debugging
console.log(qs.stringify(reportFilters, { encode: false }))
// dateRange[from]=2025-01-01&dateRange[to]=2025-03-31&status[0]=published&status[1]=archived...

// Parsing back
const parsed = qs.parse(query)
console.log(parsed.dateRange)   // { from: '2025-01-01', to: '2025-03-31' }
console.log(parsed.status)      // ['published', 'archived']

สำหรับพารามิเตอร์ key-value แบบ flat, URLSearchParamsคือตัวเลือกที่ถูกต้องเสมอ — มันมีอยู่ built-in มี overhead เป็นศูนย์ และได้รับการรองรับ ทั่วไป ใช้ qs เฉพาะเมื่อคุณต้องการ nested structures, รูปแบบ array serialisation อื่นนอกจาก repeated keys หรือคุณกำลัง integrate กับ back-end framework ที่ต้องการ query strings แบบ bracket notation

ข้อผิดพลาดทั่วไป

ฉันเห็นข้อผิดพลาดสี่ประการเหล่านี้ซ้ำๆ ใน production codebases — ส่วนใหญ่เป็นความล้มเหลว แบบเงียบที่ปรากฏเฉพาะเมื่อค่ามีตัวอักษรพิเศษ ซึ่งเป็นประเภท bug ที่หลุดผ่าน unit test และปรากฏเฉพาะกับข้อมูลผู้ใช้จริง

ข้อผิดพลาด 1 — ใช้ encodeURI() สำหรับค่า query parameter

ปัญหา: encodeURI() ไม่เข้ารหัส &, = หรือ +เมื่อค่ามีตัวอักษรเหล่านี้ ตัวอักษรเหล่านั้นจะถูกตีความเป็น query string syntax ทำให้แยกหรือเขียนทับพารามิเตอร์อย่างเงียบๆ การแก้ไข: ใช้ encodeURIComponent() สำหรับค่าแต่ละตัวเสมอ

Before · JavaScript
After · JavaScript
// ❌ encodeURI does not encode & and = in the value
//    "plan=pro&promo=SAVE20" is treated as two separate params
const planName = 'Pro Plan (save=20% & free trial)'
const url = `/checkout?plan=${encodeURI(planName)}`
// /checkout?plan=Pro%20Plan%20(save=20%%20&%20free%20trial)
//                                          ↑ & breaks the query string
// ✅ encodeURIComponent encodes & and = safely
const planName = 'Pro Plan (save=20% & free trial)'
const url = `/checkout?plan=${encodeURIComponent(planName)}`
// /checkout?plan=Pro%20Plan%20(save%3D20%25%20%26%20free%20trial)
//                                   ↑ = and & are both encoded

ข้อผิดพลาด 2 — Double-encoding string ที่เข้ารหัสแล้ว

ปัญหา: การเรียก encodeURIComponent() บนค่าที่เข้ารหัส percent แล้วจะเปลี่ยน % เป็น %25 ทำให้ %20 กลายเป็น %2520 Server ถอดรหัสครั้งเดียวและได้รับ literal %20 แทนช่องว่าง การแก้ไข: ถอดรหัสก่อน แล้วค่อยเข้ารหัสใหม่ หรือตรวจสอบให้แน่ใจว่าค่าไม่ถูกเข้ารหัสสองครั้ง

Before · JavaScript
After · JavaScript
// ❌ encodedParam already contains %20 — encoding again produces %2520
const encodedParam  = 'Berlin%20Office'
const url = `/api/locations/${encodeURIComponent(encodedParam)}`
// /api/locations/Berlin%2520Office
// Server sees: "Berlin%20Office" (a literal percent-twenty, not a space)
// ✅ Decode first if the value may already be encoded
const maybeEncoded = 'Berlin%20Office'
const clean = decodeURIComponent(maybeEncoded)  // 'Berlin Office'
const url   = `/api/locations/${encodeURIComponent(clean)}`
// /api/locations/Berlin%20Office — correct

ข้อผิดพลาด 3 — ไม่คำนึงถึงความแตกต่าง + / %20 ระหว่าง URLSearchParams และ encodeURIComponent

ปัญหา: URLSearchParams เข้ารหัสช่องว่างเป็น + (application/x-www-form-urlencoded) ในขณะที่ encodeURIComponent() ใช้ %20 การผสมทั้งสองใน URL เดียวกัน — ตัวอย่างเช่น การต่อ string ที่เข้ารหัสไว้แล้วกับ output ของ URLSearchParams — สร้างการเข้ารหัสที่ไม่สอดคล้องกัน ซึ่งทำให้ parser บางตัวสับสน การแก้ไข: เลือกวิธีหนึ่งและใช้อย่างสม่ำเสมอตลอด URL-building function

Before · JavaScript
After · JavaScript
// ❌ Mixed: URLSearchParams uses + for spaces, but we're appending
//    a manually-encoded segment that uses %20
const base   = new URLSearchParams({ category: 'office furniture' })
const extra  = `sort=${encodeURIComponent('price asc')}`
const url    = `/api/products?${base}&${extra}`
// /api/products?category=office+furniture&sort=price%20asc
//              ↑ two different space encodings in the same URL
// ✅ Use URLSearchParams exclusively — consistent encoding throughout
const params = new URLSearchParams({
  category: 'office furniture',
  sort:     'price asc',
})
const url = `/api/products?${params}`
// /api/products?category=office+furniture&sort=price+asc

ข้อผิดพลาด 4 — ลืมเข้ารหัส path segments ที่มีเครื่องหมาย slash

ปัญหา: ตัวระบุ resource อย่าง file path (reports/2025/q1.pdf) ที่ใช้เป็น REST path segment มีตัวอักษร / ที่ server router ตีความเป็น path separators ทำให้ route ไปยัง endpoint ที่ไม่มีอยู่ การแก้ไข: ใช้ encodeURIComponent() สำหรับ path segments ที่อาจมี slashes เสมอ

Before · JavaScript
After · JavaScript
// ❌ The file path contains / — the server receives a 3-segment path
//    instead of a single resource ID
const filePath = 'reports/2025/q1-financials.pdf'
const url      = `https://storage.example.com/objects/${filePath}`
// https://storage.example.com/objects/reports/2025/q1-financials.pdf
// → Server routes to /objects/:year/:filename — 404 or wrong resource
// ✅ encodeURIComponent encodes / as %2F — single path segment
const filePath = 'reports/2025/q1-financials.pdf'
const url      = `https://storage.example.com/objects/${encodeURIComponent(filePath)}`
// https://storage.example.com/objects/reports%2F2025%2Fq1-financials.pdf
// → Server receives the full file path as one resource identifier

วิธี URL Encoding ของ JavaScript — การเปรียบเทียบรวดเร็ว

วิธีเข้ารหัสช่องว่างเป็นเข้ารหัส & = ?เข้ารหัส # / :กรณีใช้งานต้องติดตั้ง
encodeURIComponent()%20✅ ใช่✅ ใช่การเข้ารหัสค่า parameter แต่ละตัวNo
encodeURI()%20❌ ไม่❌ ไม่การทำความสะอาด URL string ทั้งหมดNo
URLSearchParams+✅ ใช่✅ ใช่การสร้างและ parse query stringsNo
URL constructorอัตโนมัติตาม componentอัตโนมัติอัตโนมัติการสร้างและทำให้ URL ทั้งหมดเป็นรูปแบบมาตรฐานNo
ไลบรารี qs%20 (กำหนดค่าได้)✅ ใช่✅ ใช่Nested objects และ arrays ใน query stringsnpm install qs

สำหรับกรณีส่วนใหญ่ ตัวเลือกจะลดลงเหลือสามสถานการณ์ ใช้ URLSearchParams เมื่อสร้าง query strings หลายพารามิเตอร์จากข้อมูลที่มีโครงสร้าง — เป็นตัวเลือกที่ปลอดภัยและอ่านง่ายที่สุด ใช้ encodeURIComponent() สำหรับการเข้ารหัสค่าเดียว ใน template literal URL, สำหรับ path segments หรือสำหรับค่าในระบบที่คาดว่าจะเป็น %20 แทน + สำหรับช่องว่าง (เช่น AWS S3 signed URLs) ใช้ qs เฉพาะเมื่อ query string ของคุณมี nested objects หรือ arrays ที่ URLSearchParams ไม่สามารถแทนได้โดยตรง

คำถามที่พบบ่อย

ความแตกต่างระหว่าง encodeURIComponent() และ encodeURI() ใน JavaScript คืออะไร?
encodeURIComponent() เข้ารหัสทุกตัวอักษรยกเว้นชุดที่ไม่ถูกสงวน (A–Z, a–z, 0–9, - _ . ! ~ * ' ( )) รวมถึงตัวอักษรโครงสร้างอย่าง & = ? # / : ออกแบบมาสำหรับการเข้ารหัสค่า query parameter แต่ละตัวหรือ path segments encodeURI() รักษาตัวอักษร URL เชิงโครงสร้าง — ไม่เข้ารหัส & = ? # / : @ — เพราะออกแบบมาเพื่อทำความสะอาด URL ทั้งหมดโดยไม่ทำลายโครงสร้าง การใช้ encodeURI() บนค่าที่มี & หรือ = เป็นแหล่งทั่วไปของการเสียหายของข้อมูลอย่างเงียบๆ
ทำไม URLSearchParams ถึงเข้ารหัสช่องว่างเป็น + แทน %20?
URLSearchParams ปฏิบัติตาม specification application/x-www-form-urlencoded (เดิมมาจากการส่ง HTML form) ซึ่งเข้ารหัสช่องว่างเป็น + แทน %20 ทั้ง + และ %20 เป็นการแทนค่าที่ถูกต้องของช่องว่างใน query strings และ server ส่วนใหญ่รับทั้งสองแบบ อย่างไรก็ตาม API บางตัว — โดยเฉพาะ AWS Signature v4, Google APIs และ custom REST backends — ต้องการ %20 สำหรับกรณีเหล่านั้น ให้ใช้ encodeURIComponent() เพื่อสร้าง query string ด้วยตนเอง หรือเรียก params.toString().replace(/\+/g, '%20') บน output ของ URLSearchParams
จะ URL-encode path segment ที่มี forward slashes ใน JavaScript ได้อย่างไร?
ใช้ encodeURIComponent() — มันเข้ารหัส / เป็น %2F เปลี่ยน path ทั้งหมดให้เป็น segment เดียว encodeURI() ไม่เข้ารหัส / ดังนั้นจะถูก router ตีความเป็น path separator จริงๆ นี่สำคัญสำหรับ REST API ที่ใช้ตัวระบุ resource ในตำแหน่ง path: file paths (reports/2025/q1.pdf), S3 object keys และ composite IDs (org/team/member) หลังจากเข้ารหัส: encodeURIComponent('reports/2025/q1.pdf') → 'reports%2F2025%2Fq1.pdf'
จะถอดรหัส percent-encoded URL parameter ใน JavaScript ได้อย่างไร?
ใช้ decodeURIComponent() สำหรับค่า parameter แต่ละตัว หรือให้ URLSearchParams จัดการโดยอัตโนมัติ เมื่อคุณทำ new URLSearchParams(window.location.search).get('key') ค่าจะถูกถอดรหัสแล้ว — คุณไม่จำเป็นต้องเรียก decodeURIComponent() อีกครั้ง เรียก decodeURIComponent() โดยตรงเฉพาะเมื่อคุณได้รับ string ที่เข้ารหัสดิบนอก URLSearchParams ตัวอย่างเช่น จาก custom header หรือจาก URL fragment ที่ parse ด้วยตนเอง หมายเหตุ: decodeURIComponent() โยน URIError บน sequences ที่ผิดรูปแบบอย่างตัวอักษร % เดี่ยว — ครอบด้วย try/catch ถ้า input มาจากข้อมูลผู้ใช้
ฉันสามารถใช้ URLSearchParams เพื่อเข้ารหัส nested objects อย่าง { filters: { status: "active" } } ได้ไหม?
ไม่ได้ URLSearchParams รองรับเฉพาะคู่ key-value แบบ flat เท่านั้น มัน serialize nested object โดยเรียก .toString() บนแต่ละค่า ซึ่งสร้าง "[object Object]" — ผิดอย่างเงียบๆ สำหรับโครงสร้างที่ซ้อนกัน ให้ใช้ไลบรารี qs: qs.stringify({ filters: { status: 'active' } }) สร้าง filters%5Bstatus%5D=active (bracket notation) ซึ่งเข้าใจโดย Express, Rails และ Django REST Framework หรือจะ serialize ข้อมูลที่ซ้อนกันเป็น JSON string และส่งเป็นค่า parameter เดียว: params.set('filters', JSON.stringify({ status: 'active' }))
Fetch API เข้ารหัส query parameters โดยอัตโนมัติหรือไม่?
ไม่ fetch() รับ URL string และส่งไปยัง network layer โดยตรง — มันไม่ parse หรือเข้ารหัส query parameters ถ้าคุณเชื่อมต่อค่าที่ไม่ได้เข้ารหัสเข้ากับ URL string ตัวอักษรพิเศษจะทำให้ request เสียหาย รูปแบบที่ถูกต้องคือสร้าง URL ด้วย URLSearchParams หรือ encodeURIComponent() ก่อนส่งไปยัง fetch(): const url = new URL('/api/search', base); url.searchParams.set('q', userInput); const res = await fetch(url) URL constructor และ URLSearchParams ร่วมกันให้การเข้ารหัสอัตโนมัติที่ปลอดภัยพร้อม API ที่ชัดเจน

เครื่องมือที่เกี่ยวข้อง

สำหรับการเข้ารหัสหรือถอดรหัสด้วยคลิกเดียวโดยไม่ต้องเขียน code ให้วาง string ของคุณ ลงใน ตัวเข้ารหัส URL โดยตรง — มันจัดการ percent-encoding และการถอดรหัสได้ทันทีในเบราว์เซอร์ของคุณ พร้อม output ที่เข้ารหัสแล้วสำหรับคัดลอกไปใน fetch call หรือ terminal

AC
Alex ChenFront-end & Node.js Developer

Alex is a front-end and Node.js developer with extensive experience building web applications and developer tooling. He is passionate about web standards, browser APIs, and the JavaScript ecosystem. In his spare time he contributes to open-source projects and writes about modern JavaScript patterns, performance optimisation, and everything related to the web platform.

SL
Sophie Laurentผู้ตรวจสอบทางเทคนิค

Sophie is a full-stack developer focused on TypeScript across the entire stack — from React frontends to Express and Fastify backends. She has a particular interest in type-safe API design, runtime validation, and the patterns that make large JavaScript codebases stay manageable. She writes about TypeScript idioms, Node.js internals, and the ever-evolving JavaScript module ecosystem.