YumYumYum YumYumYum - 5 months ago 31
Javascript Question

Javascript - how to detect unknown character at begin and end?

I have stream of string where it has unkown character in begin and end.

enter image description here

How do i detect that first unknown character and the last one? I tried following but it does not match with any

\uxxxx
lists such as:

\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
?

Code:

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

}


EDIT: stream of data.
\u0002
and
\u0003
not matching.

enter image description here

EDIT: Parser is working

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

});

Answer Source

Use regex to match the pattern, example- '/([^\u0002]*+)$'.test(str);