JavaScript URL डीकोड — decodeURIComponent()

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

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

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

Percent-encoded strings JavaScript code में लगातार दिखाई देती हैं — एक search query q=standing+desk%26price%3A200 के रूप में आती है, एक OAuth redirect next=https%3A%2F%2Fdashboard.internal%2F के रूप में, एक storage path reports%2F2025%2Fq1.pdf के रूप में। JavaScript में URL decode करने का तरीका तीन built-in functions में से सही चुनने पर निर्भर करता है: decodeURIComponent(), decodeURI(), और URLSearchParams — और उनके बीच का चुनाव production codebases में मैंने जो सबसे अधिक silent data corruption देखी है उसका मूल कारण है, विशेष रूप से +-as-space edge case और double-decoding। बिना code लिखे quick one-off decode के लिए, ToolDeck का URL डिकोडर इसे browser में तुरंत handle करता है। यह JavaScript URL decoding tutorial सभी तीन functions को गहराई से cover करती है (ES2015+ / Node.js 10+): प्रत्येक का उपयोग कब करें, spaces और reserved characters के लिए वे कैसे differ करते हैं, files और HTTP requests से decoding, safe error handling, और चार mistakes जो सबसे subtle production bugs का कारण बनती हैं।

  • decodeURIComponent() सभी percent-encoded sequences को decode करता है — यह individual query parameter values और path segments के लिए सही विकल्प है
  • decodeURI() / ? & = # : जैसे structural URI characters को preserve करता है — इसे केवल complete URL string decode करते समय उपयोग करें, individual values के लिए कभी नहीं
  • URLSearchParams.get() पहले से decoded values लौटाता है — उस पर decodeURIComponent() कॉल करने से double-decoding होती है
  • decodeURIComponent() + को space के रूप में decode नहीं करता — form-encoded (application/x-www-form-urlencoded) data के लिए URLSearchParams उपयोग करें या decode से पहले + को replace करें
  • जब input user data से आता है तो decodeURIComponent() को हमेशा try/catch में लपेटें — bare % या incomplete sequence URIError throw करता है

URL Decoding क्या है?

Percent-encoding (आधिकारिक रूप से RFC 3986 में परिभाषित) उन characters को जो URL में unsafe या structurally significant हैं, एक % sign के बाद दो hexadecimal digits से replace करता है — character की UTF-8 byte value। URL decoding इस transformation को reverse करता है: प्रत्येक %XX sequence उसके original byte में वापस convert होती है, और resulting byte sequence को UTF-8 text के रूप में interpret किया जाता है। एक space %20 से decode होती है, एक slash %2F से, non-ASCII character ü %C3%BC से (इसकी two-byte UTF-8 representation)।

वे characters जो कभी encode नहीं होते — जिन्हें unreserved characters कहते हैं — हैं letters A–Z और a–z, digits 0–9, और - _ . ~। बाकी सब या तो URL में structural role रखते हैं (जैसे / path segments को separate करता है या & query parameters को) या data के रूप में उपयोग होने पर encode होना चाहिए। Practical result: एक search filter जैसे status=active&tier=premium जो single query parameter value के रूप में encode होता है, मूल से बिल्कुल अलग दिखता है।

Before · text
After · text
// Percent-encoded — HTTP request या webhook payload में प्राप्त
"q=price%3A%5B200+TO+800%5D%20AND%20brand%3ANorthwood%20%26%20status%3Ain-stock"
// URL decoding के बाद — मूल Elasticsearch query filter
"q=price:[200 TO 800] AND brand:Northwood & status:in-stock"

decodeURIComponent() — Values Decode करने का Standard Function

decodeURIComponent() JavaScript में URL decoding का workhorse है। यह input string में हर %XX sequence को decode करता है — उन characters सहित जिनका URL में structural meaning है, जैसे %2F (slash), %3F (question mark), %26 (ampersand), और %3D (equals sign)। यह इसे individual query parameter values और path segments decode करने के लिए सही विकल्प बनाता है, लेकिन complete URL decode करने के लिए गलत — जहाँ वे structural characters encoded रहने चाहिए। यह एक global function है: किसी भी JavaScript environment में कोई import की जरूरत नहीं।

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

JavaScript (browser / Node.js)
// Individual query parameter values decode करना — सामान्य मामला

const city     = decodeURIComponent('Mumbai%20Central')           // 'Mumbai Central'
const district = decodeURIComponent('Bandra%20Kurla%20Complex')   // 'Bandra Kurla Complex'
const category = decodeURIComponent('office%20furniture')         // 'office furniture'
const filter   = decodeURIComponent('price%3A%5B200+TO+800%5D')  // 'price:[200+TO+800]'
// नोट: + को space के रूप में decode नहीं किया जाता — comparison table के + section देखें

console.log(city)      // Mumbai Central
console.log(district)  // Bandra Kurla Complex
console.log(category)  // office furniture
console.log(filter)    // price:[200+TO+800]

Query parameter से extract किए गए redirect URL को decode करना

JavaScript
// Redirect URL को percent-encode किया गया था जब इसे parameter value के रूप में embed किया
// receiving end: extract करें, फिर use करें — URLSearchParams के साथ manual decoding की जरूरत नहीं

const incomingUrl = 'https://auth.company.com/callback' +
  '?next=https%3A%2F%2Fdashboard.internal%2Freports%3Fview%3Dweekly%26team%3Dplatform' +
  '&session_id=sid_7x9p2k'

const url       = new URL(incomingUrl)
const rawNext   = url.searchParams.get('next')       // URLSearchParams द्वारा Auto-decoded
const sessionId = url.searchParams.get('session_id') // 'sid_7x9p2k'

// rawNext already decoded है: 'https://dashboard.internal/reports?view=weekly&team=platform'
// decodeURIComponent(rawNext) फिर से मत कॉल करें — वह double-decoding होगी

const nextUrl = new URL(rawNext!)
console.log(nextUrl.hostname)                    // dashboard.internal
console.log(nextUrl.searchParams.get('view'))    // weekly
console.log(nextUrl.searchParams.get('team'))    // platform

Non-ASCII और Unicode path segments decode करना

JavaScript
// Internationalised path segments के साथ REST API
// मूल character के प्रत्येक UTF-8 byte को अलग से percent-encode किया गया था

const encodedSegments = [
  '%E6%9D%B1%E4%BA%AC',   // 東京  (Tokyo)   — प्रति character 3 bytes
  'M%C3%BCnchen',         // München          — ü 2 bytes के रूप में encoded
  'caf%C3%A9',            // café             — é precomposed NFC के रूप में
  'Bengaluru%20Urban',    // Bengaluru Urban
]

encodedSegments.forEach(seg => {
  console.log(decodeURIComponent(seg))
})
// 東京
// München
// café
// Bengaluru Urban

// Storage API URL से file key extract करना
// Object key में / था इसलिए इसे path segment के अंदर %2F के रूप में encode किया
const storageUrl = 'https://storage.api.example.com/v1/objects/reports%2F2025%2Fq1-financials.pdf'
const rawKey     = new URL(storageUrl).pathname.replace('/v1/objects/', '')
// .pathname URL-level encoding decode करता है लेकिन %2F (URL level पर %252F) रहता है
// अंतिम step के लिए decodeURIComponent उपयोग करें:
const fileKey = decodeURIComponent(rawKey)  // 'reports/2025/q1-financials.pdf'
console.log(fileKey)
नोट:decodeURIComponent() एक URIError throw करता है जब input में % के बाद दो valid hexadecimal digits नहीं होते — उदाहरण string के अंत में bare % या %GH जैसा sequence। User-supplied input decode करते समय इसे हमेशा try/catch में लपेटें। Safe decoding patterns नीचे Error Handling section में cover किए गए हैं।

JavaScript URL Decoding Functions — Character Reference

तीन built-in decoding functions इस बात में differ करते हैं कि वे exactly कौन से encoded sequences decode करते हैं। Table उन characters के लिए behaviour दिखाती है जो practice में सबसे ज्यादा matter करते हैं:

एन्कोडेडवर्णdecodeURIComponent()decodeURI()URLSearchParams
%20spacespace ✅space ✅space ✅
+plus (form)+ (रखा गया)+ (रखा गया)space ✅
%2B+ literal+ ✅+ ✅+ ✅
%26&& ✅& (रखा गया) ❌& ✅
%3D== ✅= (रखा गया) ❌= ✅
%3F?? ✅? (रखा गया) ❌? ✅
%23## ✅# (रखा गया) ❌# ✅
%2F// ✅/ (रखा गया) ❌/ ✅
%3A:: ✅: (रखा गया) ❌: ✅
%40@@ ✅@ (रखा गया) ❌@ ✅
%25%% ✅% ✅% ✅
%C3%BCüü ✅ü ✅ü ✅

दो critical rows हैं + और structural characters (%26, %3D, %3F)। URLSearchParams + को space के रूप में decode करता है क्योंकि यह application/x-www-form-urlencoded specification का पालन करता है — HTML form submissions के लिए सही, लेकिन जो decodeURIComponent() उसी character के साथ करता है उससे अलग। और decodeURI() चुपचाप %26, %3D, और %3F को skip करता है — जो तब तक सही लगता है जब तक कोई value वास्तव में encoded ampersand या equals sign न हो।

decodeURI() — Complete URL को उसकी Structure तोड़े बिना Decode करना

decodeURI() encodeURI() का counterpart है। यह एक complete URL string decode करता है जबकि URI में structural meaning रखने वाले characters को preserve करता है: ; , / ? : @ & = + $ #। ये अपने percent-encoded form में रहते हैं (या literal characters के रूप में यदि वे input में unencoded दिखाई दिए)। यह decodeURI() को full URLs को sanitise करने के लिए safe बनाता है जिनमें path या hostname में non-ASCII characters हो सकते हैं, बिना query string structure को accidentally collapse किए।

Non-ASCII path segments के साथ URL को Sanitise करना

JavaScript
// Internationalised path segments और structured query string के साथ CDN URL
// decodeURI() non-ASCII path decode करता है लेकिन ? & = को intact रखता है

const encodedUrl =
  'https://cdn.example.com/assets/%E6%9D%B1%E4%BA%AC%2F2025%2Fq1-report.pdf' +
  '?token=eyJ0eXAiOiJKV1QiLCJhbGci&expires=1735689600'

const readable = decodeURI(encodedUrl)
console.log(readable)
// https://cdn.example.com/assets/東京/2025/q1-report.pdf?token=eyJ0eXAiOiJKV1QiLCJhbGci&expires=1735689600
// ↑ Non-ASCII decoded; ? & = preserved — URL structurally valid रहती है

// decodeURIComponent URL को destroy कर देता — : / ? & = सब एक साथ decoded
const broken = decodeURIComponent(encodedUrl)
// 'https://cdn.example.com/assets/東京/2025/q1-report.pdf?...'
// यहाँ same दिखता है, लेकिन 'https%3A%2F%2F...' जैसा URL destroy हो जाता
नोट:जब आपको individual URL components access करने की भी जरूरत हो तो decodeURI() की बजाय URL constructor prefer करें। new URL(str) input को normalise करता है, इसकी structure validate करता है, और .pathname, .searchParams, और .hostname को already-decoded properties के रूप में expose करता है। decodeURI() को उन cases के लिए reserve करें जहाँ आपको केवल string result चाहिए और URL constructor use नहीं कर सकते (उदाहरण के लिए, बहुत पुराने Node.js 6 environments में जहाँ global URL class नहीं है)।

URLSearchParams — Query Strings के लिए Automatic Decoding

URLSearchParams modern JavaScript में query strings parse करने का idiomatic तरीका है। .get(), .getAll(), या iteration द्वारा return की गई हर value automatically decoded होती है — form-encoded data के लिए + को space सहित। यह सभी modern browsers और Node.js 10+ में globally available है, कोई import की जरूरत नहीं, और उन edge cases को handle करता है जो manual string splitting में गलत होते हैं।

Incoming query string parse करना

JavaScript (browser / Node.js 10+)
// Webhook callback या OAuth redirect query string parse करना
const rawSearch =
  '?event_id=evt_9c2f4a1b' +
  '&product_name=Standing+Desk+Pro' +
  '&filter=price%3A%5B200+TO+800%5D' +
  '&tag=ergonomic&tag=adjustable' +
  '&redirect=https%3A%2F%2Fdashboard.internal%2Forders%3Fview%3Dpending'

const params = new URLSearchParams(rawSearch)

console.log(params.get('event_id'))      // 'evt_9c2f4a1b'
console.log(params.get('product_name'))  // 'Standing Desk Pro'       ← + space के रूप में decoded
console.log(params.get('filter'))        // 'price:[200+TO+800]'      ← %3A और %5B decoded
console.log(params.getAll('tag'))        // ['ergonomic', 'adjustable']
console.log(params.get('redirect'))      // 'https://dashboard.internal/orders?view=pending'

// सभी parameters iterate करना
for (const [key, value] of params) {
  console.log(`${key}: ${value}`)
}
// event_id: evt_9c2f4a1b
// product_name: Standing Desk Pro
// filter: price:[200+TO+800]
// tag: ergonomic
// tag: adjustable
// redirect: https://dashboard.internal/orders?view=pending

Current browser URL से query parameters parse करना

JavaScript (browser)
// Current URL: https://app.example.com/search
//   ?q=standing+desk
//   &category=office+furniture
//   &sort=price_asc
//   &page=2

interface SearchFilters {
  query:    string | null
  category: string | null
  sort:     string
  page:     number
}

function getSearchFilters(): SearchFilters {
  const params = new URLSearchParams(window.location.search)
  return {
    query:    params.get('q'),                       // 'standing desk'
    category: params.get('category'),                // 'office furniture'
    sort:     params.get('sort') ?? 'relevance',
    page:     Number(params.get('page') ?? '1'),
  }
}

const filters = getSearchFilters()
console.log(filters.query)     // standing desk   (+ automatically decoded)
console.log(filters.category)  // office furniture

Files और API Responses से URL-Encoded Data Decode करना

दो scenarios real projects में बार-बार आते हैं: disk पर एक file process करना जिसमें percent-encoded data है (access logs, data exports, webhook capture files), और Node.js server में incoming HTTP request का URL parse करना। दोनों एक ही principle follow करते हैं — manual string splitting की बजाय URL constructor या URLSearchParams use करें — लेकिन details differ करते हैं।

File से URL-encoded records पढ़ना और decode करना

JavaScript (Node.js 10+)
import { createReadStream } from 'fs'
import { createInterface } from 'readline'

// File: orders-export.txt — प्रति line एक URL-encoded record
// customer_name=%E0%A4%B0%E0%A4%BE%E0%A4%B9%E0%A5%81%E0%A4%B2+%E0%A4%B6%E0%A4%B0%E0%A5%8D%E0%A4%AE%E0%A4%BE&order_id=ord_9c2f4a&product=Standing+Desk+Pro&total=12499%20INR
// customer_name=%E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%BF%E0%A4%AF%E0%A4%BE+%E0%A4%97%E0%A5%81%E0%A4%AA%E0%A5%8D%E0%A4%A4%E0%A4%BE&order_id=ord_7b3a1c&product=Ergonomic+Chair&total=8499%20INR
// customer_name=Arjun+Verma&order_id=ord_2e8d5f&product=Monitor+Arm&total=3299%20INR

interface Order {
  customerName: string | null
  orderId:      string | null
  product:      string | null
  total:        string | null
}

async function parseOrdersFile(filePath: string): Promise<Order[]> {
  const fileStream = createReadStream(filePath, { encoding: 'utf-8' })
  const rl         = createInterface({ input: fileStream, crlfDelay: Infinity })
  const orders: Order[] = []

  for await (const line of rl) {
    if (!line.trim()) continue

    // URLSearchParams + को space और %XX sequences को automatically decode करता है
    const params = new URLSearchParams(line)

    orders.push({
      customerName: params.get('customer_name'),  // 'राहुल शर्मा'
      orderId:      params.get('order_id'),        // 'ord_9c2f4a'
      product:      params.get('product'),         // 'Standing Desk Pro'
      total:        params.get('total'),           // '12499 INR'
    })
  }

  return orders
}

const orders = await parseOrdersFile('./orders-export.txt')
console.log(orders[0])
// { customerName: 'राहुल शर्मा', orderId: 'ord_9c2f4a', product: 'Standing Desk Pro', total: '12499 INR' }

Search queries decode करने के लिए Nginx access log parse करना

JavaScript (Node.js)
import { createReadStream } from 'fs'
import { createInterface } from 'readline'

// Nginx access log lines इस तरह दिखती हैं:
// 192.168.1.42 - - [11/Mar/2026:10:23:01 +0000] "GET /api/search?q=standing%20desk%26brand%3ANorthwood&sort=price_asc HTTP/1.1" 200 1842

async function extractSearchQueries(logFile: string): Promise<string[]> {
  const rl     = createInterface({ input: createReadStream(logFile), crlfDelay: Infinity })
  const queries: string[] = []

  for await (const line of rl) {
    // Log line से request path extract करें
    const match = line.match(/"GET ([^ ]+) HTTP/)
    if (!match) continue

    try {
      const requestUrl = new URL(match[1], 'http://localhost')
      const query      = requestUrl.searchParams.get('q')
      if (query) queries.push(query)  // URLSearchParams automatically decode करता है
    } catch {
      // Malformed lines skip करें — access logs में truncated entries हो सकती हैं
    }
  }

  return queries
}

const queries = await extractSearchQueries('/var/log/nginx/access.log')
console.log(queries)
// ['standing desk&brand:Northwood', 'ergonomic chair', 'monitor arm 27 inch']

Node.js HTTP server में query parameters parse करना

JavaScript (Node.js 10+)
import http from 'http'

// Incoming URL: /api/products?q=standing+desk&warehouse=mumbai%2Dwest&minStock=10&cursor=eyJpZCI6MTIzfQ%3D%3D

const server = http.createServer((req, res) => {
  // Full URL construct करें — दूसरा arg URL constructor के लिए जरूरी base है
  const requestUrl = new URL(req.url!, 'http://localhost')

  const searchQuery = requestUrl.searchParams.get('q')            // 'standing desk'
  const warehouseId = requestUrl.searchParams.get('warehouse')    // 'mumbai-west'
  const minStock    = Number(requestUrl.searchParams.get('minStock') ?? '0')
  const cursor      = requestUrl.searchParams.get('cursor')       // 'eyJpZCI6MTIzfQ=='

  if (!warehouseId) {
    res.writeHead(400, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ error: 'warehouse parameter आवश्यक है' }))
    return
  }

  const cursorData = cursor ? JSON.parse(Buffer.from(cursor, 'base64').toString()) : null

  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ searchQuery, warehouseId, minStock, cursorData }))
})

server.listen(3000)

जब आपको development के दौरान एक encoded URL inspect करने की जरूरत हो — यह समझने के लिए कि parsing code लिखने से पहले webhook क्या भेज रहा है — इसे directly ToolDeck का URL डिकोडर में paste करें ताकि script run किए बिना तुरंत decoded form देख सकें।

Command-Line URL Decoding

Shell scripts, CI pipelines, या encoded strings की quick one-off inspection के लिए, कई approaches पूरी script लिखे बिना काम करते हैं। Node.js one-liners cross-platform हैं; macOS और Linux पर python3 भी हमेशा available है।

bash
# ── Node.js one-liners ──────────────────────────────────────────────────

# Single percent-encoded value decode करना
node -e "console.log(decodeURIComponent(process.argv[1]))" "Mumbai%20%26%20Delhi"
# Mumbai & Delhi

# Query string parse करना और हर key=value pair (decoded) print करना
node -e "
  const params = new URLSearchParams(process.argv[1])
  for (const [k, v] of params) console.log(`${k} = ${v}`)
" "q=standing+desk&warehouse=bengaluru%2Dnorth&minStock=10"
# q = standing desk
# warehouse = bengaluru-north
# minStock = 10

# URL-encoded JSON body decode और pretty-print करना (webhook debugging में common)
node -e "
  const raw = decodeURIComponent(process.argv[1])
  console.log(JSON.stringify(JSON.parse(raw), null, 2))
" '%7B%22event%22%3A%22purchase%22%2C%22amount%22%3A149.99%2C%22currency%22%3A%22INR%22%7D'
# {
#   "event": "purchase",
#   "amount": 149.99,
#   "currency": "INR"
# }

# ── Python one-liner (अधिकांश macOS/Linux systems पर available) ─────────────
# unquote_plus + को भी space के रूप में decode करता है — form-encoded data के लिए सही
python3 -c "
from urllib.parse import unquote_plus
import sys
print(unquote_plus(sys.argv[1]))
" "Standing+Desk+%26+Ergonomic+Chair"
# Standing Desk & Ergonomic Chair

# ── curl — response header से redirect URL log और decode करना ──────────
curl -sI "https://api.example.com/short/abc123" | grep -i location |   node -e "
    const line = require('fs').readFileSync('/dev/stdin', 'utf8')
    const url  = line.replace(/^location:s*/i, '').trim()
    console.log(decodeURIComponent(url))
  "

decode-uri-component के साथ Graceful Decoding

Built-in decodeURIComponent() किसी भी malformed sequence पर URIError throw करता है — trailing % सहित जिसके बाद दो hex digits नहीं हैं। Production code में जो user-supplied या third-party URLs process करता है — search query logs, email campaigns के clickthrough URLs, scraped web data — malformed sequences crashes के लिए काफी common हैं। decode-uri-component package (~30M weekly npm downloads) malformed sequences को gracefully handle करता है — throw करने की बजाय original sequence unchanged return करके।

bash
npm install decode-uri-component
# या
pnpm add decode-uri-component
JavaScript (Node.js)
import decodeUriComponent from 'decode-uri-component'

// Native function invalid input पर throw करता है — request handler crash हो सकता है
try {
  decodeURIComponent('product%name%')   // ❌ URIError: URI malformed
} catch (e) {
  console.error('Native ने throw किया:', (e as Error).message)
}

// decode-uri-component throw करने की बजाय raw sequence return करता है
console.log(decodeUriComponent('product%name%'))
// product%name%   ← malformed sequences as-is रहते हैं, throw नहीं होता

// Valid sequences correctly decode होते हैं
console.log(decodeUriComponent('Mumbai%20%26%20Delhi'))
// Mumbai & Delhi

// Mixed: valid sequences decoded, invalid ones preserved
console.log(decodeUriComponent('Delhi%20NCR%20%ZZ%20Region'))
// Delhi NCR %ZZ Region   ← %ZZ valid hex नहीं — as-is रहता है

// Log processing pipeline में practical use
const rawSearchQueries = [
  'standing%20desk%20ergonomic',
  'price%3A%5B200+TO+800%5D',
  '50%25+off',       // ← decodeURIComponent के साथ throw होता (bare %)
  'wireless%20keyboard%20%26%20mouse',
]

const decoded = rawSearchQueries.map(q => decodeUriComponent(q))
console.log(decoded)
// ['standing desk ergonomic', 'price:[200+TO+800]', '50%25+off', 'wireless keyboard & mouse']

Application code के लिए जहाँ आप तुरंत जानना चाहते हैं कि unexpected input आया है, try/catch के साथ decodeURIComponent() use करें। Data pipelines, log processors, और webhook handlers में decode-uri-component use करें जहाँ आप कुछ inputs में invalid encoding होने पर भी processing जारी रखना चाहते हैं।

Malformed Percent-Encoded Strings को Handle करना

Bare %, incomplete sequence जैसे %A, या invalid pair जैसे %GH सभी decodeURIComponent() को URIError: URI malformed throw करवाते हैं। कोई भी user-controlled input — search queries, URL fragments, form fields containing URLs, email campaign links के parameters — इन sequences को contain कर सकता है। किसी भी externally-facing code के लिए safe wrapper ज़रूरी है।

Common scenarios के लिए Safe decode wrappers

JavaScript
// ── 1. Basic safe decode — error पर original string return करता है ─────────
function safeDecode(encoded: string): string {
  try {
    return decodeURIComponent(encoded)
  } catch {
    return encoded  // decoding fail होने पर raw input return करें — कभी crash नहीं
  }
}

// ── 2. Safe decode + form-encoded values के लिए + को space handle करना ─────────
function safeFormDecode(formEncoded: string): string {
  try {
    return decodeURIComponent(formEncoded.replace(/+/g, ' '))
  } catch {
    return formEncoded.replace(/+/g, ' ')  // कम से कम + replace करें बाकी fail हो तो भी
  }
}

// ── 3. Safe full query string parser → plain object ──────────────────────
function parseQueryString(queryString: string): Record<string, string> {
  const result: Record<string, string> = {}
  try {
    const params = new URLSearchParams(queryString)
    for (const [key, value] of params) {
      result[key] = value  // URLSearchParams internally सभी decoding handle करता है
    }
  } catch {
    // Completely malformed input पर silently empty return करें
  }
  return result
}

// Usage
console.log(safeDecode('Mumbai%20Central'))          // Mumbai Central
console.log(safeDecode('search%20for%2050%25+off'))  // search for 50% off (bare %)
                                                     // → actually fine; यहाँ % %25 है
console.log(safeDecode('malformed%string%'))         // malformed%string%  (throw नहीं)

console.log(safeFormDecode('standing+desk+pro'))     // standing desk pro

console.log(parseQueryString('q=hello+world&tag=node%20js&page=2'))
// { q: 'hello world', tag: 'node js', page: '2' }

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

मैंने इन चार patterns को production में silent data corruption या unexpected crashes का कारण बनते देखा है — आमतौर पर केवल तब जब कोई value किसी special character को contain करती है, जिसका मतलब है कि वे unit tests से बाहर निकल जाती हैं और real user data के साथ सामने आती हैं।

गलती 1 — URLSearchParams value को Double-decode करना

समस्या: URLSearchParams.get() एक already-decoded string return करता है। उस पर decodeURIComponent() कॉल करने से value double-decode होती है — decoded output में किसी भी बचे % को %25 में बदल देती है, जो data corrupt करती है। सुधार: URLSearchParams.get() से value directly use करें — कोई additional decoding की जरूरत नहीं।

Before · JavaScript
After · JavaScript
// ❌ URLSearchParams already decoded — फिर से decode करने से % वाली values corrupt होती हैं
const qs        = new URLSearchParams('rate=50%25&redirect=https%3A%2F%2Fdashboard.internal%2F')
const rawRate   = qs.get('rate')       // '50%'   ← already decoded
const wrongRate = decodeURIComponent(rawRate)
// '50%25'  ← % दूसरे pass पर %25 में decoded हो गया — अब फिर गलत
// ✅ URLSearchParams.get() directly use करें — decoding automatic है
const qs       = new URLSearchParams('rate=50%25&redirect=https%3A%2F%2Fdashboard.internal%2F')
const rate     = qs.get('rate')        // '50%'   ← सही, कोई extra step नहीं
const redirect = qs.get('redirect')    // 'https://dashboard.internal/'
const parsed   = new URL(redirect!)    // Construct करना safe — already decoded
console.log(parsed.hostname)           // dashboard.internal

गलती 2 — Form-encoded data के लिए + को space के रूप में decode न करना

समस्या: Form submissions और कुछ OAuth libraries spaces को + (application/x-www-form-urlencoded) के रूप में encode करते हैं। इस data पर decodeURIComponent() call करने से + literal plus sign के रूप में रहता है। सुधार: form-encoded data parse करने के लिए URLSearchParams use करें, या decodeURIComponent() call करने से पहले + को space से replace करें।

Before · JavaScript
After · JavaScript
// ❌ decodeURIComponent + को literal plus treat करता है, space नहीं
// OAuth token endpoint send करता है: grant_type=authorization_code&code=SplxlOBeZQQYb...
//   &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
// कुछ legacy OAuth implementations + को spaces के लिए use करते हैं
const formBody   = 'customer_name=%E0%A4%B0%E0%A4%BE%E0%A4%B9%E0%A5%81%E0%A4%B2+%E0%A4%B6%E0%A4%B0%E0%A5%8D%E0%A4%AE%E0%A4%BE&product=Standing+Desk+Pro&qty=2'
const [, rawVal] = formBody.split('&')[0].split('=')
const name       = decodeURIComponent(rawVal)
console.log(name)  // 'राहुल+शर्मा'  ← + space में convert नहीं हुआ
// ✅ URLSearchParams use करें — application/x-www-form-urlencoded spec follow करता है
const formBody   = 'customer_name=%E0%A4%B0%E0%A4%BE%E0%A4%B9%E0%A5%81%E0%A4%B2+%E0%A4%B6%E0%A4%B0%E0%A5%8D%E0%A4%AE%E0%A4%BE&product=Standing+Desk+Pro&qty=2'
const params     = new URLSearchParams(formBody)
console.log(params.get('customer_name'))  // 'राहुल शर्मा'   ← + correctly space के रूप में decoded
console.log(params.get('product'))        // 'Standing Desk Pro'

गलती 3 — Individual query parameter values के लिए decodeURI() use करना

समस्या: decodeURI() %26 (&), %3D (=), या %3F (?) को decode नहीं करता — ये characters parameter values के अंदर commonly encoded होते हैं। इसे single value decode करने के लिए use करने से वे sequences intact रहती हैं, चुपचाप incorrect output produce करता है। सुधार: individual values के लिए decodeURIComponent() use करें; decodeURI() को full URL strings के लिए reserve करें।

Before · JavaScript
After · JavaScript
// ❌ decodeURI & और = decode नहीं करता — value broken रहती है
const encodedFilter = 'status%3Dactive%26tier%3Dpremium%26region%3Deu-west'
const filter        = decodeURI(encodedFilter)
console.log(filter)
// 'status%3Dactive%26tier%3Dpremium%26region%3Deu-west'  ← %3D और %26 decoded नहीं
// ✅ decodeURIComponent & और = सहित सभी sequences decode करता है
const encodedFilter = 'status%3Dactive%26tier%3Dpremium%26region%3Deu-west'
const filter        = decodeURIComponent(encodedFilter)
console.log(filter)
// 'status=active&tier=premium&region=eu-west'  ← correctly decoded

गलती 4 — User input के लिए decodeURIComponent को try/catch में न लपेटना

समस्या: Bare %जिसके बाद दो hex digits नहीं — users द्वारा type की गई search queries में common (“50% off”, “100% cotton”) — decodeURIComponent() को URIError: URI malformed throw करवाता है, uncaught होने पर request handler crash हो जाता है। सुधार: जब input user data, URL fragments, या external systems से आता हो तो हमेशा try/catch में लपेटें।

Before · JavaScript
After · JavaScript
// ❌ User ने search box में '100% cotton' type किया — bare % server crash करता है
// GET /api/search?q=100%25+cotton  ← यह specific case ठीक है (%25 = %)
// GET /api/search?q=100%+cotton    ← यह crash करता है (% के बाद 2 hex digits नहीं)
app.get('/api/search', (req, res) => {
  const query = decodeURIComponent(req.query.q as string)
  // ↑ '100% cotton' के लिए URIError: URI malformed throw करता है → unhandled 500 error
})
// ✅ try/catch में लपेटें — decoding fail होने पर raw input पर fallback करें
app.get('/api/search', (req, res) => {
  let query: string
  try {
    query = decodeURIComponent(req.query.q as string)
  } catch {
    query = req.query.q as string  // crash होने की बजाय raw value use करें
  }
  // safely processing continue करें — query either decoded या raw है
})

decodeURIComponent vs decodeURI vs URLSearchParams — त्वरित तुलना

विधि%XX Decode करता है+ को space Decode करता हैMalformed पर Throw करता है& = ? # Decode करता हैउपयोग मामलाInstall चाहिए
decodeURIComponent()✅ सभी❌ नहीं✅ URIError✅ हाँIndividual values और path segmentsNo
decodeURI()✅ अधिकांश❌ नहीं✅ URIError❌ नहींComplete URL stringsNo
URLSearchParams✅ सभी✅ हाँ❌ silent✅ हाँAutomatic decode के साथ query string parsingNo
URL constructor✅ सभी✅ हाँ✅ TypeError✅ हाँFull URL parsing और normalisationNo
decode-uri-component✅ सभी❌ नहीं❌ silent✅ हाँMalformed-input tolerance के साथ batch decodenpm install
querystring.unescape()✅ सभी❌ नहीं❌ silent✅ हाँLegacy Node.js (v16 में deprecated)No (built-in)

अधिकांश cases के लिए, choice तीन scenarios में reduce हो जाती है। Query strings parse करने के लिए URLSearchParams use करें — यह decoding, +-as-space rule, और repeated keys को automatically handle करता है। Single value या path segment के लिए (wrapped in try/catch) decodeURIComponent() use करें, विशेष रूप से जब आप segment के अंदर %2F-encoded slashes expect करते हैं। decodeURI() केवल तभी use करें जब आपके पास complete URL string हो जिसके path में non-ASCII characters हों और आपको structural characters (/ ? & =) output में encoded रखना हो।

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

JavaScript में decodeURIComponent() और decodeURI() के बीच क्या अंतर है?
decodeURIComponent() string में हर percent-encoded sequence decode करता है, उन characters सहित जिनका URL में structural meaning है — & (%26), = (%3D), ? (%3F), # (%23), / (%2F), और : (%3A)। यह individual query parameter values या path segments decode करने के लिए designed है। decodeURI() उन structural characters को preserve करता है — %26, %3D, %3F, %23, %2F, या %3A decode नहीं करता — क्योंकि यह complete URL को उसकी query string structure तोड़े बिना sanitise करने के लिए designed है। किसी single parameter value पर जिसमें encoded & या = हो decodeURI() use करने से वे sequences silently undecoded रहते हैं, गलत output produce करते हैं।
कुछ strings के लिए decodeURIComponent() URIError क्यों throw करता है?
decodeURIComponent() URIError: URI malformed throw करता है जब input में % के बाद exactly दो valid hexadecimal digits नहीं होते। Common triggers: string के अंत में bare % ("50% off" user द्वारा type किया), incomplete sequence ("%A"), या non-hex pair ("%GH")। यह सबसे अधिक user-typed search queries या ऐसे values के साथ होता है जो text से paste किए गए जो कभी URL-encoded होने के लिए intended नहीं था। Fix है decodeURIComponent() को try/catch block में लपेटना और error पर raw string return करना। decode-uri-component npm package try/catch wrapper की जरूरत के बिना same fix offer करता है।
क्या URLSearchParams automatically percent-encoded values decode करता है?
हाँ। URLSearchParams.get() और URLSearchParams.getAll() द्वारा return की गई हर value fully decoded होती है — आपको उनके output पर decodeURIComponent() कभी नहीं call करना चाहिए। URLSearchParams application/x-www-form-urlencoded specification भी follow करता है, जो + को space decode करता है, इसे HTML form submissions और OAuth token responses के लिए correct बनाता है। एकमात्र case जहाँ URLSearchParams help नहीं कर सकता वह है standalone encoded value decode करना जो query string का part नहीं — उसके लिए, try/catch के साथ decodeURIComponent() use करें।
JavaScript में + sign को space के रूप में कैसे decode करें?
decodeURIComponent() + को literal plus sign treat करता है — + को space में convert नहीं करता। यह intentional है: + as space एक application/x-www-form-urlencoded convention है, percent-encoding standard से अलग। + को space decode करने के लिए, URLSearchParams use करें (जो form-encoded spec follow करता है), या decodeURIComponent() call करने से पहले + replace करें: decodeURIComponent(str.replace(/\+/g, ' '))। नोट करें कि decode से पहले + को %20 से replace करना भी काम करता है लेकिन थोड़ा more verbose है। Full query strings parse करने के लिए हमेशा URLSearchParams prefer करें — यह %20 और + दोनों को correctly handle करता है।
Node.js में URL string को कैसे decode करें?
वही global functions use करें जो सभी browsers में available हैं — Node.js 10+ में कोई import की जरूरत नहीं। Individual values के लिए decodeURIComponent(), complete URL strings के लिए decodeURI(), query strings के लिए URLSearchParams। Incoming HTTP request URLs के लिए, new URL(req.url, 'http://localhost') use करें — URL constructor URL को normalise करता है और .searchParams (auto-decoded) और .pathname (URL level पर decoded) expose करता है। पुराना querystring.unescape() function अभी भी exist करता है लेकिन Node.js 16 से deprecated है — decodeURIComponent() prefer करें।
JavaScript में URL query string को object में कैसे parse करें?
Object.fromEntries() के साथ URLSearchParams use करें: const params = Object.fromEntries(new URLSearchParams(queryString))। यह सभी parameter keys और decoded values के साथ एक plain object देता है। नोट करें कि Object.fromEntries() duplicate keys के लिए केवल last value रखता है — tag=one&tag=two जैसे repeated keys के लिए, URLSearchParams.getAll('tag') use करें। Browser के लिए, new URLSearchParams(window.location.search) current page की query string automatically parse करता है। Node.js के लिए, new URL(req.url, base).searchParams से parse करें।

संबंधित टूल

बिना कोई code लिखे one-click decode के लिए, अपनी percent-encoded string को directly ToolDeck का URL डिकोडर में paste करें — यह browser में तुरंत decode करता है, result आपके code या terminal में copy करने के लिए ready।

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.

MW
Marcus Webbतकनीकी समीक्षक

Marcus specialises in JavaScript performance, build tooling, and the inner workings of the V8 engine. He has spent years profiling and optimising React applications, working on bundler configurations, and squeezing every millisecond out of critical rendering paths. He writes about Core Web Vitals, JavaScript memory management, and the tools developers reach for when performance really matters.