Hey everyone quick question, I know this sounds strange to do in javascript but i have good use for it. I need to be able to parse a string passed in a textarea in such a way that escaped hex literals "\x41" or whatever are processed not as four chars '\' 'x' '4' '1' but as 'A' for example:
var anA = "\x41";
console.log(anA); //emits "A"
var stringToParse = $(#someTextArea).val(); //using jquery for ease not a req
//lets say that "someTextArea" contains "\x41"
console.log(stringToParse); // equals "\" "x" "4" "1" -- not what i want
console.log(new String(stringToParse)); same as last
console.log(""+stringToParse); still doesnt work
console.log(stringToParse.toString()); failz all over (same result)
I want to be able to have a way for stringToParse to contain "A" not "\x41"... any ideas beyond regex? I'll take a regex i guess, i just wanted a way to make javascript do my bidding :)
Hey everyone quick question, I know this sounds strange to do in javascript but i have good use for it. I need to be able to parse a string passed in a textarea in such a way that escaped hex literals "\x41" or whatever are processed not as four chars '\' 'x' '4' '1' but as 'A' for example:
var anA = "\x41";
console.log(anA); //emits "A"
var stringToParse = $(#someTextArea).val(); //using jquery for ease not a req
//lets say that "someTextArea" contains "\x41"
console.log(stringToParse); // equals "\" "x" "4" "1" -- not what i want
console.log(new String(stringToParse)); same as last
console.log(""+stringToParse); still doesnt work
console.log(stringToParse.toString()); failz all over (same result)
I want to be able to have a way for stringToParse to contain "A" not "\x41"... any ideas beyond regex? I'll take a regex i guess, i just wanted a way to make javascript do my bidding :)
Share Improve this question asked Apr 26, 2012 at 2:07 RyanRyan 2,82518 silver badges30 bronze badges 02 Answers
Reset to default 6String.prototype.parseHex = function(){
return this.replace(/\\x([a-fA-F0-9]{2})/g, function(a,b){
return String.fromCharCode(parseInt(b,16));
});
};
and in practice:
var v = $('#foo').val();
console.log(v);
console.log(v.parseHex());
I figured it out although its kind of hacky and i use eval :(... if anyone has a better way let me know:
stringToParse = stringToParse.toSource().replace("\\x", "\x");
stringToParse = eval(stringToParse);
console.log(stringToParse);
mainly i needed this to parse mixed strings... as in string literals with hex mixed in