Sử dụng encodeURI()
Để mã hóa một URL hoàn chỉnh, dùng encodeURI(). Hàm này không mã hóa các ký tự dành riêng cho URL như : / ? # [ ] @.
Ví dụ
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Encode</button>
<p id="demo"></p>
<script>
function display() {
var url = "welcome msg.jsp?name=\u00E5mit&sub=programming";
var result = encodeURI(url);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
Kết quả
welcome%20msg.jsp?name=%C3%A5mit&sub=programming
Lưu ý quan trọng
- encodeURI(): Dùng cho URL đầy đủ.
- encodeURIComponent(): Dùng cho tham số (query string) – mã hóa cả
&,=,?.
Ví dụ: encodeURIComponent("a=b&c") → a%3Db%26c.