2012-04-26 41 views
2

嘿大家快速的问题,我知道这听起来很奇怪,在JavaScript中做,但我有很好的使用它。我需要能够解析在textarea中传递的字符串,使得转义的十六进制文字“\ x41”或任何不是被处理为四个字符'\''x''4''1',而是作为'A'例如:解析javascript中的十六进制文字

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) 

我希望能够有stringToParse办法遏制“A”而不是“\ X41” ......正则表达式以外的任何想法?我会带一个正则表达式我想,我只是想办法让JavaScript的做我的竞标:)

+0

我也尝试过valueOf() – Ryan 2012-04-26 02:10:59

回答

6
String.prototype.parseHex = function(){ 
    return this.replace(/\\x([a-fA-F0-9]{2})/g, function(a,b){ 
     return String.fromCharCode(parseInt(b,16)); 
    }); 
}; 

,并在实践:

var v = $('#foo').val(); 
console.log(v); 
console.log(v.parseHex()); 
+1

实际上,因为它们应该是十六进制数,'// \ x([a-f0-9] {2})/ gi'也可以工作(并且不区分大小写)。 – GregL 2012-04-26 02:16:59

+0

@GregL:这很有趣,我以为a-f,但显然没有贯彻。谢谢你的到来,咖啡在这里耗尽。 ;-) – 2012-04-26 02:17:53

+0

我也喜欢你的方法......谢谢你...... – Ryan 2012-04-26 02:28:19

1

我想通了,虽然它的种类哈克和在字符串

stringToParse = stringToParse.toSource().replace("\\x", "\x"); 
stringToParse = eval(stringToParse); 
console.log(stringToParse); 

主要是我需要这个来解析混合串......与十六进制的

混合:我使用eval:(......如果任何人有一个更好的方式让我知道3210
+1

Eww,'eval'是邪恶的。 – 2012-04-26 02:32:55

+0

是的......我知道......这就是为什么我选择了另一个...为我的目的工作......我欣赏帮助家伙 – Ryan 2012-04-26 02:34:39