温馨提示×

url转义字符的方法有哪些

url
小亿
161
2023-06-19 09:44:45
栏目: 编程语言

  1. 使用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"
  1. 手动替换特殊字符,将特殊字符替换为它们的转义字符。例如:
"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"
  1. 使用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"

0