我正在使用 Javascript 在钛中开发一个应用程序。我需要 Javascript 中 encodeURIComponent
的开源实现。
任何人都可以指导我或向我展示一些实现方法吗?
最佳答案
此函数的规范在 15.1.3.4 中.
V8 的现代版本 (2018) 使用 C++ 实现它。参见 src/uri.h :
// ES6 section 18.2.6.5 encodeURIComponenet (uriComponent)
static MaybeHandle<String> EncodeUriComponent(Isolate* isolate,
Handle<String> component) {
调用uri.cc中定义的Encode
.
V8 的旧版本是用 JavaScript 实现的,并在 BSD 许可下分发。参见 src/uri.js 的第 359 行.
// ECMA-262 - 15.1.3.4
function URIEncodeComponent(component) {
var unescapePredicate = function(cc) {
if (isAlphaNumeric(cc)) return true;
// !
if (cc == 33) return true;
// '()*
if (39 <= cc && cc <= 42) return true;
// -.
if (45 <= cc && cc <= 46) return true;
// _
if (cc == 95) return true;
// ~
if (cc == 126) return true;
return false;
};
var string = ToString(component);
return Encode(string, unescapePredicate);
}
它没有被称为 encodeURIComponent
,但是这个代码在同一个文件中,建立了映射:
InstallFunctions(global, DONT_ENUM, $Array(
"escape", URIEscape,
"unescape", URIUnescape,
"decodeURI", URIDecode,
"decodeURIComponent", URIDecodeComponent,
"encodeURI", URIEncode,
"encodeURIComponent", URIEncodeComponent
));
关于javascript - encodeURIComponent算法源码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9635661/