- 使用encodeURIComponent()函數,它可以將任意字符串轉換為URL安全的字符串。例如:
encodeURIComponent("http://www.example.com/?name=張三&age=20")
// "http%3A%2F%2Fwww.example.com%2F%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20"
- 手動替換特殊字符,將特殊字符替換為它們的轉義字符。例如:
"http://www.example.com/?name=張三&age=20".replace(/:/g, '%3A').replace(/\//g, '%2F').replace(/\?/g, '%3F').replace(/&/g, '%26')
// "http%3A%2F%2Fwww.example.com%2F%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20"
- 使用ES6的template strings語法,將字符串包裹在反引號(`)中,并使用${}來插入變量。例如:
const name = '張三'
const age = 20
`http://www.example.com/?name=${encodeURIComponent(name)}&age=${age}`
// "http://www.example.com/?name=%E5%BC%A0%E4%B8%89&age=20"