Created
August 2, 2022 12:30
-
-
Save ikawka/ca3d6506010e94e1326eb4a07bd0ffab to your computer and use it in GitHub Desktop.
Handle string with with octal escape sequences
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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