Javascript八进制转义字符转中文


读取git输出时,发现当设置core.quotepath=false时,输出的中文会被转义为8进制。不更改设置的话,需要手动转回中文。

源代码

function Octal2Chinese(str) {
  const matches = str.match(/(\\\d{3}){3}/g);
  if (matches) matches.forEach(match => {
    let encoded = '';
    const splits = match.split('\\');
    splits.forEach(code => !code || (encoded += '%' + parseInt(code, 8).toString(16)));
    const cChar = decodeURI(encoded);
    str = str.replace(match, cChar);
  });
  return str;
}

测试结果

console.log(Octal2Chinese('\\344\\270\\255\\346\\226\\207'))
// >> 中文
相关标签

扫一扫

在手机上阅读