js對(duì)url進(jìn)行編碼解碼的方式有哪些

js
小億
91
2024-03-08 15:03:25

  1. 使用encodeURIComponent()和decodeURIComponent()函數(shù):
// 編碼
var encodedUrl = encodeURIComponent("https://www.example.com?name=張三&age=20");
console.log(encodedUrl); // https%3A%2F%2Fwww.example.com%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20

// 解碼
var decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=張三&age=20
  1. 使用encodeURI()和decodeURI()函數(shù):
// 編碼
var encodedUrl = encodeURI("https://www.example.com?name=張三&age=20");
console.log(encodedUrl); // https://www.example.com?name=%E5%BC%A0%E4%B8%89&age=20

// 解碼
var decodedUrl = decodeURI(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=張三&age=20
  1. 使用escape()和unescape()函數(shù)(不推薦使用,已被廢棄):
// 編碼
var encodedUrl = escape("https://www.example.com?name=張三&age=20");
console.log(encodedUrl); // https%3A%2F%2Fwww.example.com%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20

// 解碼
var decodedUrl = unescape(encodedUrl);
console.log(decodedUrl); // https://www.example.com?name=張三&age=20

0