Skip to content

Instantly share code, notes, and snippets.

@ikawka
Created August 2, 2022 12:30
Show Gist options
  • Save ikawka/ca3d6506010e94e1326eb4a07bd0ffab to your computer and use it in GitHub Desktop.
Save ikawka/ca3d6506010e94e1326eb4a07bd0ffab to your computer and use it in GitHub Desktop.
Handle string with with octal escape sequences
const hexToAscii = str => {
return str
.match(/.{2}/g)
.reduce(
(current, substr) => current + String.fromCharCode(parseInt(substr, 16)),
'',
)
.replaceAll(/\x00|\\b|\n|\r/g, ''); // remove unwanted characters
};
const checkHex = str => {
const regex1 = str.match(new RegExp('(\\X2).*(\\X0)', 'igm'))
return !!regex1 ? regex1[0] : false;
}
const str = String.raw`\X2\00D8\X0\600 SPUN PILE`
let words = str.split(' ')
words = words.reduce((curr, w) => {
const match = checkHex(w)
if(match !== false) {
curr.push(w.replace(match, hexToAscii(match.replaceAll(/\\/g, ''))).replaceAll(/\\/g, ''))
} else {
curr.push(w)
}
return curr
}, [])
console.log(words.join(' ')) // Ø600 SPUN PILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment