ใช้ encodeURI() สำหรับเข้ารหัส URL ทั้งหมด และ encodeURIComponent() สำหรับเข้ารหัสส่วนประกอบ (query params, path segments)
ตัวอย่างจากบทความ
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Encode</button>
<p id="demo"></p>
<script>
function display() {
var encode = "welcome msg.jsp?name=\u00e5mit&sub=programming";
var result = encodeURI(encode);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
encodeURI() vs encodeURIComponent()
| ฟังก์ชัน | ใช้สำหรับ | เข้ารหัส | ไม่เข้ารหัส |
|---|---|---|---|
encodeURI() | URL ทั้งหมด | Space, Unicode, 特殊字符 | : / ? # [ ] @ ! $ & ' ( ) * + , ; = |
encodeURIComponent() | ส่วนประกอบ (query, param) | ทุกตัวยกเว้น A-Z a-z 0-9 - _ . ! ~ * ' ( ) | - |
ตัวอย่างเปรียบเทียบ
var url = "https://example.com/search?q=hello world&lang=th"; // encodeURI - เก็บโครงสร้าง URL ไว้ encodeURI(url); // "https://example.com/search?q=hello%20world&lang=th" // encodeURIComponent - เข้ารหัสทุกอย่างรวมถึง & = ? encodeURIComponent(url); // "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dhello%20world%26lang%3Dth" // ใช้ encodeURIComponent สำหรับ query parameter var param = "hello world&special=chars"; var safeUrl = "https://example.com/search?q=" + encodeURIComponent(param); // "https://example.com/search?q=hello%20world%26special%3Dchars"
ตัวอย่างการใช้งานจริง
1. สร้าง Query String
function buildUrl(base, params) {
const query = Object.entries(params)
.map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v))
.join('&');
return base + '?' + query;
}
buildUrl('/api/search', { q: 'hello world', lang: 'th', page: 1 });
// "/api/search?q=hello%20world&lang=th&page=1"
2. URLSearchParams (Modern API)
const params = new URLSearchParams();
params.append('q', 'hello world');
params.append('lang', 'th');
console.log(params.toString()); // "q=hello+world&lang=th"
// หมายเหตุ: ใช้ + แทน space (application/x-www-form-urlencoded)
// ใช้กับ URL
const url = new URL('https://example.com/search');
url.search = params;
console.log(url.href); // "https://example.com/search?q=hello+world&lang=th"
3. Decode (ถอดรหัส)
decodeURI(encodedUrl); // คู่กับ encodeURI decodeURIComponent(encodedParam); // คู่กับ encodeURIComponent
สรุปเมื่อไหร่ใช้ไหน
- encodeURI() - URL เต็มที่มีโครงสร้างครบ (protocol, domain, path)
- encodeURIComponent() - ค่า parameter, query string, path segment เดี่ยว
- URLSearchParams - สร้าง query string อัตโนมัติ (Modern, แนะนำ)