我正在开发一个使用Javascript的钛合金应用程序。我需要一个在Javascript的encodeURIComponent开源实现。
有没有人可以指导我或者向我展示一些实现?
发布于 2012-03-09 22:48:41
此函数的规范在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
));发布于 2012-03-09 22:31:57
你需要encodeuricomponent做什么?它已经存在于JS中。
无论如何,这里有一个实现的例子:
http://phpjs.org/functions/rawurlencode:501#comment_93984
发布于 2018-12-03 20:28:19
下面是我的实现:
var encodeURIComponent = function( str ) {
var hexDigits = '0123456789ABCDEF';
var ret = '';
for( var i=0; i<str.length; i++ ) {
var c = str.charCodeAt(i);
if( (c >= 48/*0*/ && c <= 57/*9*/) ||
(c >= 97/*a*/ && c <= 122/*z*/) ||
(c >= 65/*A*/ && c <= 90/*Z*/) ||
c == 45/*-*/ || c == 95/*_*/ || c == 46/*.*/ || c == 33/*!*/ || c == 126/*~*/ ||
c == 42/***/ || c == 92/*\\*/ || c == 40/*(*/ || c == 41/*)*/ ) {
ret += str[i];
}
else {
ret += '%';
ret += hexDigits[ (c & 0xF0) >> 4 ];
ret += hexDigits[ (c & 0x0F) ];
}
}
return ret;
};https://stackoverflow.com/questions/9635661
复制相似问题