js url转义的方法
将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()不会对#符号进行转义
原文地址: https://www.cveoy.top/t/topic/dnSW 著作权归作者所有。请勿转载和采集!