Javascript八进制转义字符转中文

2018-03-07  本文已影响688人  平仄_pingze

读取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'))
// >> 中文
上一篇 下一篇

猜你喜欢

热点阅读