【问题标题】:encodeURIComponent algorithm source codeencodeURIComponent算法源码
【发布时间】:2012-03-09 14:28:15
【问题描述】:

我正在使用 Javascript 在钛中开发应用程序。我需要 Javascript 中 encodeURIComponent 的开源实现。

有人可以指导我或向我展示一些实现吗?

【问题讨论】:

标签: javascript encoding titanium


【解决方案1】:

这个函数的规范在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
  ));

【讨论】:

  • 但你也调用 Encode I just everything plain JavaScript
  • 你有更新的源链接吗?我自己找不到实现。我打算将它移植到 D(如 C++ 之类的语言)。
  • @spikespaz,代码现在是原生的。请参阅同一目录中的uri.huri.cc
【解决方案2】:

这是我的实现:

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;
};

【讨论】:

    【解决方案3】:

    你需要encodeuricomponent做什么?它已经存在于 JS 中。

    不管怎样,这里是一个实现的例子:

    http://phpjs.org/functions/rawurlencode:501#comment_93984

    【讨论】:

    • 是的,它在 JS 中,但我需要将它作为我项目的一部分开源,顺便说一下你提供的方法不起作用
    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2023-01-18
    • 2012-10-13
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多