How can I take a string like
John, Smith~2C John, Jones~2CMike
And replace these hex values indicated by ~ with their ASCII counterparts?
How can I take a string like
John, Smith~2C John, Jones~2CMike
And replace these hex values indicated by ~ with their ASCII counterparts?
Assuming you always have 2 char hex-codes preceded by char ~
, then /~[0-9A-F]{2}/i
will give a match.
Now if we match globally and attach a function to replace, we can parse the integer using radix/base 16 and generate a character (using Object String's method fromCharCode
) from that. Just don't forget to strip the trailing ~
character first.
Here is a short example to get you started:
function demo(s){
return s.replace(/~[0-9A-F]{2}/gi, function(m){
return String.fromCharCode(parseInt(m.slice(1), 16));
});
}
console.log( demo('John, Smith~2C John, Jones~2CMike') );
Hope this helps!