URL Encode JavaScript — encodeURIComponent() गाइड

·Front-end & Node.js Developer·समीक्षकSophie Laurent·प्रकाशित

मुफ़्त URL Encode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।

URL Encode Online ऑनलाइन आज़माएं →

जब आप एक सर्च URL बनाते हैं, एक redirect पथ को query पैरामीटर के रूप में पास करते हैं, या OAuth ऑथराइज़ेशन रिक्वेस्ट बनाते हैं, तो &, =, और स्पेस जैसे विशेष वर्ण URL को चुपचाप नष्ट कर देंगे जब तक आप पहले URL एन्कोडिंग नहीं करते। JavaScript तीन बिल्ट-इन तरीके प्रदान करता है — encodeURIComponent(), encodeURI(), और URLSearchParams — प्रत्येक एक अलग उपयोग मामले के लिए डिज़ाइन किया गया है, और गलत को चुनना अधिकांश एन्कोडिंग बग्स का मूल कारण है जो मैंने कोड समीक्षाओं में पाए हैं। किसी भी कोड के बिना त्वरित एन्कोडिंग के लिए, ToolDeck का URL एन्कोडर इसे ब्राउज़र में तुरंत संभालता है। यह गाइड सभी तीन तरीकों को गहराई से कवर करती है (JavaScript ES2015+ / Node.js 10+): प्रत्येक का उपयोग कब करें, रिक्त स्थान और आरक्षित वर्णों के लिए वे कैसे भिन्न हैं, Fetch और API के वास्तविक दुनिया के पैटर्न, CLI उपयोग, और चार गलतियाँ जो सबसे सूक्ष्म प्रोडक्शन बग का कारण बनती हैं।

  • encodeURIComponent() अलग-अलग पैरामीटर मानों को एन्कोड करने के लिए सही विकल्प है — यह A–Z, a–z, 0–9 और - _ . ! ~ * ' ( ) को छोड़कर हर वर्ण को एन्कोड करता है
  • encodeURI() संरचनात्मक वर्णों (/ ? # & = :) को सुरक्षित रखते हुए एक पूर्ण URL को एन्कोड करता है — इसे कभी भी अलग-अलग मानों के लिए उपयोग न करें
  • URLSearchParams application/x-www-form-urlencoded फ़ॉर्मेट का उपयोग करके कुंजी-मूल्य जोड़ों को स्वतः एन्कोड करता है, जहाँ रिक्त स्थान %20 की बजाय + बन जाते हैं
  • Double-encoding सबसे सामान्य प्रोडक्शन बग है: encodeURIComponent(encodeURIComponent(value)) %20 को %2520 में बदल देता है
  • qs लाइब्रेरी query string में नेस्टेड ऑब्जेक्ट और arrays को नेटिव रूप से संभालती है — मानक URLSearchParams यह नहीं करता

URL Encoding क्या है?

URL encoding (जिसे आधिकारिक रूप से percent-encoding कहा जाता है, जो RFC 3986 में परिभाषित है) उन वर्णों को जो URL में अनुमत नहीं हैं या जिनका विशेष अर्थ है, एक सुरक्षित प्रतिनिधित्व में बदलता है। प्रत्येक असुरक्षित बाइट को एक प्रतिशत चिह्न के बाद दो हेक्साडेसिमल अंकों — वर्ण का ASCII कोड — से बदल दिया जाता है। एक स्पेस %20 बन जाता है, एम्परसेंड %26 बन जाता है, फॉरवर्ड स्लैश %2F बन जाता है।

वे वर्ण जो हमेशा सुरक्षित होते हैं और कभी एन्कोड नहीं किए जाते, अनारक्षित वर्ण कहलाते हैं: अक्षर A–Z और a–z, अंक 0–9, और चार प्रतीक - _ . ~। बाकी सब कुछ या तो डेटा के रूप में उपयोग किए जाने पर एन्कोड किया जाना चाहिए, या URL में ही एक संरचनात्मक भूमिका है (जैसे / पथ खंडों को अलग करता है या &query पैरामीटर अलग करता है)। व्यावहारिक परिणाम: “Wireless 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() JavaScript में URL encoding का मुख्य आधार है। यह अनारक्षित सेट (A–Z, a–z, 0–9, - _ . ! ~ * ' ( )) को छोड़कर हर वर्ण को एन्कोड करता है। महत्वपूर्ण रूप से, यह उन सभी वर्णों को एन्कोड करता है जिनका URLs में संरचनात्मक अर्थ है — &, =, ?, #, / — जो इसे पैरामीटर मानों में उपयोग के लिए सुरक्षित बनाता है। किसी import की आवश्यकता नहीं है; यह सभी JavaScript परिवेशों में उपलब्ध एक global फ़ंक्शन है।

न्यूनतम कार्यशील उदाहरण

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

Redirect URL को 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 = 'Sharma, Rahul'
const productTitle = '東京 wireless adapter'
const reviewText   = 'बहुत अच्छा — बिल्कुल सही काम करता है'

console.log(encodeURIComponent(customerName))
// Sharma%2C%20Rahul

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

console.log(encodeURIComponent(reviewText))
// %E0%A4%AC%E0%A4%B9%E0%A5%81%E0%A4%A4%20...

// Decoding back
console.log(decodeURIComponent('Sharma%2C%20Rahul'))
// Sharma, Rahul
नोट:encodeURIComponent() JavaScript इंजन की आंतरिक UTF-16 स्ट्रिंग एन्कोडिंग का उपयोग करता है, फिर वर्ण के प्रत्येक UTF-8 बाइट को अलग से एन्कोड करता है। ü (U+00FC) जैसा वर्ण %C3%BC में एन्कोड होता है क्योंकि इसका UTF-8 प्रतिनिधित्व दो बाइट है: 0xC3 और 0xBC। यह सही है और URI मानक का पालन करता है — सर्वर से अपेक्षित है कि वह UTF-8 बाइट अनुक्रम को वापस मूल codepoint में डीकोड करे।

JavaScript URL Encoding Functions — वर्ण संदर्भ

तीन native एन्कोडिंग तरीके इस बात में भिन्न हैं कि वे कौन से वर्णों को एन्कोड करते हैं। नीचे दी गई तालिका सबसे अधिक समस्याग्रस्त वर्णों के लिए आउटपुट दिखाती है:

वर्णURL में भूमिकाencodeURIComponent()encodeURI()URLSearchParams
Spaceशब्द विभाजक%20%20+
&पैरामीटर विभाजक%26रखा गया%26
=key=value%3Dरखा गया%3D
+एन्कोडेड स्पेस (form)%2B%2B%2B
?query शुरुआत%3Fरखा गया%3F
#खंड%23रखा गया%23
/पथ विभाजक%2Fरखा गया%2F
:स्कीम / पोर्ट%3Aरखा गया%3A
@प्रमाणीकरण विभाजक%40रखा गया%40
%प्रतिशत चिह्न%25%25%25
~अनारक्षितरखा गयारखा गयारखा गया

महत्वपूर्ण कॉलम है encodeURIComponent() बनाम encodeURI() के लिए & और =: encodeURI() उन्हें अछूता छोड़ देता है, जो एक पूरे URL को एन्कोड करते समय सही है लेकिन एक मान को एन्कोड करते समय विनाशकारी है जिसमें ये वर्ण होते हैं।

encodeURI() — URL संरचना कब संरक्षित करें

encodeURI() एक पूर्ण URL को एन्कोड करने के लिए डिज़ाइन किया गया है — यह URI के सभी वैध संरचनात्मक भागों को संरक्षित करता है: scheme (https://), host, पथ विभाजक, query सीमांक, और fragment पहचानकर्ता। इसका उपयोग तब करें जब आपको एक ऐसा URL मिले जिसमें पथ खंडों में स्पेस या non-ASCII वर्ण हो सकते हैं, लेकिन आपको उसकी संरचना बरकरार रखनी है।

उपयोगकर्ता द्वारा प्रदान की गई 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
नोट:URL constructor आमतौर पर उपयोगकर्ता द्वारा प्रदान की गई URL strings को संभालने के लिए encodeURI() से बेहतर विकल्प है — यह URL को नॉर्मलाइज़ करता है, संरचना को validate करता है, और आपको प्रत्येक घटक तक पहुँचने के लिए एक साफ API देता है। encodeURI() को केवल उन मामलों के लिए रखें जहाँ आपको एक स्ट्रिंग परिणाम की आवश्यकता है और आप पहले से जानते हैं कि इनपुट संरचनात्मक रूप से एक वैध URL है।

URLSearchParams — Query Strings के लिए आधुनिक दृष्टिकोण

URLSearchParams आधुनिक JavaScript में query strings बनाने और parse करने का मुहावरेदार तरीका है। यह सभी आधुनिक ब्राउज़रों और Node.js 10+ में globally उपलब्ध है, और एन्कोडिंग को स्वतः संभालता है — आप सादे key-value जोड़ों के साथ काम करते हैं और यह सही आउटपुट देता है। एक महत्वपूर्ण विवरण: यह application/x-www-form-urlencoded स्पेसिफिकेशन का पालन करता है, जो स्पेस को %20 की बजाय + के रूप में एन्कोड करता है। यह सही है और व्यापक रूप से समर्थित है, लेकिन जब आपका सर्वर एक विशिष्ट format की अपेक्षा रखता है तो इसके बारे में जागरूक रहें।

खोज अनुरोध 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

आने वाली query string को parse करना

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']

JavaScript Fetch Requests में URL Parameters कैसे Encode करें

प्रोडक्शन कोड में URL encoding सबसे आम जगह fetch() calls के अंदर दिखाई देती है — या तो request URL बनाने में या request body में form data भेजने में। प्रत्येक परिदृश्य का अपना सही तरीका है।

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-encoded 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()
}

जब आपको कोई स्क्रिप्ट सेटअप किए बिना एक एन्कोडेड URL को test या debug करना हो, तो raw मान को सीधे URL एन्कोडर में paste करें — यह तुरंत encode और decode करता है, और आपको ठीक वही दिखाता है जो ब्राउज़र और सर्वर देखेंगे। OAuth redirect URIs, webhook callback URLs, और CDN signed request parameters की जाँच के लिए उपयोगी।

Node.js और Shell के साथ Command-Line URL Encoding

Shell scripts, CI pipelines, या त्वरित debugging के लिए, पूरी स्क्रिप्ट लिखे बिना कई command-line तरीके काम करते हैं।

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 नेस्टेड ऑब्जेक्ट या arrays को सपोर्ट नहीं करता — जो कई APIs और frameworks द्वारा उपयोग किए जाने वाले query strings का shape है। qs library (30M+ weekly npm downloads) वास्तविक दुनिया में उपयोग किए जाने वाले query string patterns की पूरी श्रृंखला को संभालती है: bracket notation के साथ नेस्टेड ऑब्जेक्ट (filters[status]=active), repeated keys, custom encoders, और configurable array serialisation formats।

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']

Flat key-value parameters के लिए, URLSearchParams हमेशा सही विकल्प है — यह बिल्ट-इन है, शून्य overhead है, और universally supported है।qs का उपयोग केवल तभी करें जब आपको नेस्टेड structures, repeated keys के अलावा array serialisation formats, या किसी ऐसे back-end framework के साथ integrate करना हो जो bracket-notation query strings की अपेक्षा रखता है।

सामान्य गलतियाँ

मैंने इन चार गलतियों को प्रोडक्शन codebases में बार-बार देखा है — अधिकांश silent failures हैं जो केवल तभी सामने आती हैं जब एक मान में कोई विशेष वर्ण हो, जो ठीक उस प्रकार का bug है जो unit tests से बाहर निकल जाता है और केवल वास्तविक user data के साथ दिखाई देता है।

गलती 1 — query parameter values के लिए encodeURI() का उपयोग करना

समस्या: encodeURI() &, =, या + को एन्कोड नहीं करता। जब कोई मान इन वर्णों को शामिल करता है, तो उन्हें query string syntax के रूप में interpret किया जाता है, जो चुपचाप parameters को विभाजित या overwrite कर देता है। सुधार: अलग-अलग मानों के लिए हमेशा 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 — पहले से एन्कोडेड string को Double-encoding करना

समस्या: किसी ऐसे मान पर encodeURIComponent() कॉल करना जो पहले से percent-encoded है, % को %25 में बदल देता है, इसलिए %20 बन जाता है %2520। सर्वर एक बार decode करता है और एक space की बजाय literal %20 प्राप्त करता है। सुधार: पहले decode करें, फिर re-encode करें, या सुनिश्चित करें कि मान कभी दो बार एन्कोड न हो।

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 — URLSearchParams और encodeURIComponent के बीच + / %20 अंतर को नज़रअंदाज़ करना

समस्या: URLSearchParams spaces को + (application/x-www-form-urlencoded) के रूप में एन्कोड करता है, जबकि encodeURIComponent() %20 का उपयोग करता है। दोनों को एक ही URL में मिलाना — उदाहरण के लिए, एक pre-encoded string को URLSearchParams output में append करना — असंगत encoding उत्पन्न करता है जो कुछ parsers को confuse करता है। सुधार: एक दृष्टिकोण चुनें और URL-building function में इसे consistently उपयोग करें।

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 — Slashes वाले path segments को encode करना भूल जाना

समस्या: एक resource identifier जैसे file path (reports/2025/q1.pdf) जब REST path segment के रूप में उपयोग किया जाता है, तो / वर्ण होते हैं जिन्हें server router path separators के रूप में interpret करता है, एक non-existent endpoint पर route करते हुए। सुधार: उन path segments के लिए हमेशा encodeURIComponent() का उपयोग करें जिनमें 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

JavaScript URL Encoding Methods — त्वरित तुलना

विधिSpaces को एन्कोड करता है& = ? एन्कोड करता है# / : एन्कोड करता हैउपयोग मामलाInstall चाहिए
encodeURIComponent()%20✅ हाँ✅ हाँअलग-अलग parameter values एन्कोड करनाNo
encodeURI()%20❌ नहीं❌ नहींपूर्ण URL string को sanitise करनाNo
URLSearchParams+✅ हाँ✅ हाँQuery strings बनाना और parse करनाNo
URL constructorcomponent के अनुसार autoautoautoपूरे URLs को construct और normalise करनाNo
qs library%20 (configurable)✅ हाँ✅ हाँQuery strings में nested objects और arraysnpm install qs

अधिकांश मामलों के लिए, यह विकल्प तीन परिदृश्यों में सरल हो जाता है। structured data से multi-parameter query strings बनाते समय URLSearchParams का उपयोग करें — यह सबसे सुरक्षित और सबसे readable विकल्प है। template literal URL में एक single value, path segments, या ऐसी प्रणालियों में मानों के लिए encodeURIComponent() का उपयोग करें जो spaces के लिए + की बजाय %20 अपेक्षित करती हैं (जैसे AWS S3 signed URLs)। qs का उपयोग केवल तभी करें जब आपके query string में nested objects या arrays हों जिन्हें URLSearchParams natively represent नहीं कर सकता।

अक्सर पूछे जाने वाले प्रश्न

JavaScript में encodeURIComponent() और encodeURI() के बीच क्या अंतर है?
encodeURIComponent() अनारक्षित सेट (A–Z, a–z, 0–9, - _ . ! ~ * ' ( )) को छोड़कर हर वर्ण को एन्कोड करता है, जिसमें & = ? # / : जैसे संरचनात्मक वर्ण शामिल हैं। यह अलग-अलग query parameter values या path segments को एन्कोड करने के लिए डिज़ाइन किया गया है। encodeURI() संरचनात्मक URL वर्णों को संरक्षित करता है — यह & = ? # / : @ को एन्कोड नहीं करता — क्योंकि यह एक पूरे URL को उसकी संरचना तोड़े बिना sanitise करने के लिए डिज़ाइन किया गया है। किसी ऐसे मान पर encodeURI() का उपयोग करना जिसमें & या = हो, silent data corruption का एक सामान्य स्रोत है।
URLSearchParams spaces को %20 की बजाय + के रूप में क्यों एन्कोड करता है?
URLSearchParams application/x-www-form-urlencoded specification (मूल रूप से HTML form submissions से व्युत्पन्न) का पालन करता है, जो spaces को %20 की बजाय + के रूप में एन्कोड करता है। + और %20 दोनों query strings में space के valid representations हैं, और अधिकांश सर्वर दोनों को accept करते हैं। हालाँकि, कुछ APIs — विशेष रूप से AWS Signature v4, Google APIs, और custom REST backends — %20 की आवश्यकता रखते हैं। उन मामलों के लिए, query string को manually बनाने के लिए encodeURIComponent() का उपयोग करें, या URLSearchParams output पर params.toString().replace(/\+/g, '%20') कॉल करें।
JavaScript में forward slashes वाले path segment को URL-encode कैसे करें?
encodeURIComponent() का उपयोग करें — यह / को %2F के रूप में एन्कोड करता है, पूरे पथ को एक single segment में बदल देता है। encodeURI() / को एन्कोड नहीं करता, इसलिए इसे router द्वारा real path separator के रूप में treat किया जाएगा। यह REST APIs के लिए महत्वपूर्ण है जो path position में resource identifiers का उपयोग करते हैं: file paths (reports/2025/q1.pdf), S3 object keys, और composite IDs (org/team/member)। एन्कोडिंग के बाद: encodeURIComponent('reports/2025/q1.pdf') → 'reports%2F2025%2Fq1.pdf'.
JavaScript में percent-encoded URL parameter को decode कैसे करें?
अलग-अलग parameter values के लिए decodeURIComponent() का उपयोग करें, या URLSearchParams को इसे automatically handle करने दें। जब आप new URLSearchParams(window.location.search).get('key') करते हैं, तो मान पहले से decoded होता है — आपको उस पर फिर से decodeURIComponent() कॉल करने की आवश्यकता नहीं है। decodeURIComponent() को directly तभी कॉल करें जब आप URLSearchParams के बाहर raw encoded string प्राप्त करते हैं, उदाहरण के लिए एक custom header से या manually parse किए गए URL fragment से। नोट: decodeURIComponent() malformed sequences जैसे bare % character पर URIError throw करता है — यदि input user data से आता है तो इसे try/catch में लपेटें।
क्या मैं { filters: { status: "active" } } जैसे nested objects को encode करने के लिए URLSearchParams का उपयोग कर सकता हूँ?
नहीं। URLSearchParams केवल flat key-value pairs को support करता है। यह प्रत्येक मान पर .toString() कॉल करके nested object को serialize करता है, जो "[object Object]" produce करता है — चुपचाप गलत। Nested structures के लिए, qs library का उपयोग करें: qs.stringify({ filters: { status: 'active' } }) filters%5Bstatus%5D=active (bracket notation) produce करता है, जो Express, Rails, और Django REST Framework द्वारा समझा जाता है। वैकल्पिक रूप से, nested data को JSON string के रूप में serialize करें और इसे एक single parameter value के रूप में pass करें: params.set('filters', JSON.stringify({ status: 'active' })).
क्या Fetch API query parameters को automatically URL-encode करता है?
नहीं। fetch() एक URL string accept करता है और इसे verbatim नेटवर्क layer को pass करता है — यह query parameters को parse या encode नहीं करता। यदि आप URL string में un-encoded values concatenate करते हैं, तो special characters request को corrupt कर देंगे। सही pattern है fetch() को pass करने से पहले URLSearchParams या encodeURIComponent() के साथ URL बनाना: const url = new URL('/api/search', base); url.searchParams.set('q', userInput); const res = await fetch(url). URL constructor और URLSearchParams मिलकर आपको clean API के साथ safe automatic encoding देते हैं।

संबंधित टूल

बिना कोई कोड लिखे one-click encode या decode के लिए, अपनी string को सीधे URL एन्कोडर में paste करें — यह आपके ब्राउज़र में तुरंत percent-encoding और decoding संभालता है, जिसमें एन्कोडेड output fetch call या terminal में copy करने के लिए तैयार होता है।

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.