当前位置: 首页 > 科技观察

为什么'-x1B'.length===1?-x和-u知识扩展

时间:2023-03-15 08:26:32 科技观察

背景先说背景,再说原因。大部分库都会使用chalk库对日志中控制台的内容进行着色。经过chalk处理后,原来的内容会被'\x1B...'console.log(chalk.blue('green'));console.log([chalk.blue('green')]);开发vite-plugin-monitor[1]时,为了获取原始日志内容(着色前),需要还原着色后的字符串\x1B[34mgreen\x1B[39m=>green使用正则表达式处理时发现问题内容'\x1B'.replace(/\\x/,'')//result??通过.length查看其长度,结果如题所示。之所以反斜杠“\”通常标识转义字符,如\n(换行符)、\t(制表符)、\x标识十六进制,其后跟两个十六进制数同时,\u也是一个十六进制数,但是后面需要跟四个十六进制数,所以这里的\x1B其实就是一个字符'\x41'==='A'//true'A'==='\u0041'//true\x\xhh匹配一个由两位十六进制数(\x00-\xFF)表示的字符主要用在ASCII码中[2]表示'\x41'==='A''A'===String.fromCharCode(65)'\x61'==='a''a'===String.fromCharCode(97)\x后面必须跟两个十六进制字符,否则会报错,其中A-F不区分大小写'\x1'//UncaughtSyntaxError:Invalidhexadecimalescapesequence'\xfg'//UncaughtSyntaxError:Invalidhexadecimalescapesequence\u\uhhhh匹配一个由基数(\u0000-\uFFFF)表示的四位十六进制Unicode字符。常见于正则表达式匹配汉字constr=/[\u4e00-\u9fa5]/r.test('Chinese')//truer.test('English')//false正则字符和Unicode字符互换str2Unicode使用String.prototype.charCodeAt获取指定位置的Unicode码位(十进制表示),并使用String.prototype.toString将其转换为十六进制字符。转换为十六进制字符不会自动补0,通过String.prototype.padStart补0一般处理方法如下functionstr2Unicode(str){lets=''for(constcofstr){s+=`\\u${c.charCodeAt(0).toString(16).padStart(4,'0')}`}返回}str2Unicode('1aChinese')//'\\u0031\\u0061\\u4e2d\\u6587'unicode2Str匹配所有unicode字符通过正则化/\\u[\da-f]{4}/g使用Number将0x${matchStr}转换为十进制数使用String.fromCodePoint将unicode码点转换为字符使用String.prototype.replace进行逐字符转换函数str2Unicode(str){lets=''for(constcofstr){s+=`\\u${c.charCodeAt(0).toString(16).padStart(4,'0')}`}returns}str2Unicode('1aChinese')//'\\u0031\\u0061\\u4e2d\\u6587'还原chalk处理后的字符串,写一个从0-1的正则化。难免会有很多边界条件没有考虑好,于是在chalk的README中找到了chalk/ansi-regex[3]库。与值相关的ANSI转义码匹配importansiRegexfrom'ansi-regex';'\u001B[4mcake\u001B[0m'.match(ansiRegex());//=>['\u001B[4m','\u001B[0m']'\u001B[4mcake\u001B[0m'.match(ansiRegex({onl??yFirst:true}));//=>['\u001B[4m']写一个处理方法函数resetChalkStr(str){returnstr.replace(一个siRegex(),'')}testconsole.log(chalk.green('green'),chalk.greenBright('greenBright'));console.log([chalk.green('green'),chalk.greenBright('greenBright')]);console.log(resetChalkStr(`${chalk.green('green')}${chalk.greenBright('greenBright')}`));总结重温了\x和\u相关的内容,突然想到一个补充点,用\u做字符串的加解密(下来再划一遍)解决一个粉笔-相关问题“恢复终端中的彩色内容”参考[1]vite-plugin-monitor:https://github.com/ATQQ/vite-plugin-monitor[2]ASCII码:https://tool.oschina。net/commons?type=4[3]chalk/ansi-regex:https:https://github.com/chalk/ansi-regex