我参考了github上的一个插件:cookies,在该代码的第73行,是设置并格式化cookie对象的一个函数。
这段代码如何理解:
value = (value + '').replace(/[^!#$&-+\--:<-\[\]-~]/g, encodeURIComponent);
直接这么做:encodeURIComponent(value)也没啥区别啊!
求解释。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
/[^!#$&-+\--:<-\[\]-~]/g的含义是:除了!#$&-+\--:<-\[\]-~以外的其它字符。也就是说,对于#、&一类的字符不 encode。比如
"测#&+试".replace(/[^!#$&-+\--:<-\[\]-~]/g, encodeURIComponent);返回%E6%B5%8B#&+%E8%AF%95;而encodeURIComponent("测#&+试")返回%E6%B5%8B%23%26%2B%E8%AF%95。我的理解是,在这个场合,
#、&等等特殊字符是无害的。只有%、=、;等特殊字符是有害的,可能造成语法错误。安利下: 浅谈escape、encodeURI、encodeURIComponent的区别