How to convert utf-8 string to urlencoded win1251 in javascript

前端 未结 3 2127
我在风中等你
我在风中等你 2021-01-01 02:30

I have a string, for instance \"холодильник\" and looking for a way to convert it to url encoded win1251 string which is %F5%EE%EB%EE%E4%E8%EB%FC%ED%E8%EA

3条回答
  •  悲&欢浪女
    2021-01-01 02:53

    I have my own method. It's a little bit tricky but without a huge Array of charset table (assuming that your page is in "CP1251" encoding):

    // "special" chars
    var charEncodeCache = {
      ' ': '%20',
      '+': '%2B',
      '%': '%25',
      '&': '%26',
      '=': '%3D'
    };
    
    function encodeURIComponent1251(str) {
      if(!str) return str;
    
      var result = '';
    
      for(var i = 0; i < str.length; i++) {
        var char = str.charAt(i);
        if(typeof(charEncodeCache[char]) != 'undefined') {
          result += charEncodeCache[char];
        } else {
          var utfEncode = encodeURIComponent(char);
          if(utfEncode.charAt(0) == '%' && utfEncode.indexOf('%', 1) > -1) {
            /// it's two-byte UTF-char, we should convert it
            if(!this.__encode_anchor) this.__encode_anchor = document.createElement('a');
            this.__encode_anchor = "http://" + document.domain + "/encoded_str=?" + char;
            var encodedChar = this.__encode_anchor.href.split('encoded_str=?')[1];
            charEncodeCache[char] = encodedChar;
            result += encodedChar;
          } else {
            /// single byte char, just adding it to result
            result += char;
          }
        }
      }
      return result;
    }
    

    And it's a little bit faster than unicodeToWin1251_UrlEncoded ;-)

    http://jsperf.com/encode-from-utf-to-cp1251

    Not too much, but still faster and you'll have a great economy on the sources weight.

提交回复
热议问题