Javascript - 如何在开始和结束时检测未知字符?

时间:2017-08-17 06:00:19

标签: javascript jquery encoding utf-8 character-encoding

我有一个字符串流,它在开头和结尾都有未知的字符。

enter image description here

我如何检测第一个未知字符和最后一个?我尝试过关注,但它与任何\uxxxx列表不匹配,例如:

\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f

代码:

var ab2str = function(buf) {
      var bufView = new Uint8Array(buf);
      var encodedString = String.fromCharCode.apply(null, bufView);
      return decodeURIComponent(escape(encodedString));
    };

function in(data) {

  var ch = ab2str(data); ch = ch.toString('utf8');
  switch (ch) {
          case "\u0002":
            console.log('>>> STARTED');
            break; 

          case "\u0003":
            console.log('>>> ENDED');
            break;

           default:
              //var WINDOWS_1252 = '\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ';

              console.log('????????? why always default ???????');
           break;
         }

}

编辑:数据流。 \u0002\u0003不匹配。

enter image description here

编辑: Parser正在运作

  serial.onReceive.addListener(function(receiveInfo) {
    if (receiveInfo.connectionId !== connectionId) {
      console.log("FAIL: connectionId mismatch");
      return;
    }

    var ch = ab2str(receiveInfo.data);
    ch = ch.toString('utf8');       
    var check = ch.charCodeAt(0);

    if(check == 2) {
      console.log('>>> STARTED');
      lineBuffer = "";  
    }

    switch (ch) {
      default:          
        lineBuffer += ab2str(receiveInfo.data);
        console.log('>>> ???: ' , ab2str(receiveInfo.data));

        var check_end = lineBuffer.charCodeAt(lineBuffer.length-1);
        if(check_end == 3) {
          var cake = lineBuffer.substring(1);
           cake = cake.substring(0,cake.length-1);
          console.log('>>> CAKE: ' , cake);
          lineBuffer = "";
        }
        break;
    }       

  });

1 个答案:

答案 0 :(得分:0)

使用正则表达式匹配模式, 例- '/([^ \ U0002] * +)$' 测试(STR);