将 URL 中的特殊字符转义为' %xx' 的格式,其中 xx 是字符的 ASCII 码的 16 进制表示。可以使用 JavaScript 的 encodeURIComponent() 函数进行 URL 转义。例如:

var url = 'http://example.com/?q=hello world';
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl); // 'http%3A%2F%2Fexample.com%2F%3Fq%3Dhello%20world'

另外,还可以使用 encodeURI() 函数对整个 URL 进行转义,但是它不会对特殊字符如斜杠、冒号等进行转义,因为它们在 URL 中有特殊意义。如果需要对整个 URL 进行转义,可以使用以下方法:

var url = 'http://example.com/?q=hello world';
var encodedUrl = encodeURI(url).replace(/#/g, '%23');
console.log(encodedUrl); // 'http://example.com/%3Fq%3Dhello%20world'

注意,这里使用了 replace() 函数将 # 符号进行了转义,因为 encodeURI() 不会对 # 符号进行转义。

JavaScript URL 转义:使用 encodeURIComponent 和 encodeURI

原文地址: https://www.cveoy.top/t/topic/nEvi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录