url转义字符的方法有哪些

url
1789
2023/6/23 9:44:45
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  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"

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: url与sql注入有什么关系