[英]Javascript: escape %d in string
I've got the following code in Node.js: 我在Node.js中有以下代码:
var str = '',
ch;
for(/*standard for loop*/){
// some code ...
ch = '%' + buffer[i].toString(16);
str += ch;
}
Now when buffer[i].toString(16)
returns, let's say d6
, resulting string doesn't contain %d6
, but NaN6
instead. 现在,当buffer[i].toString(16)
返回时,假设d6
,得到的字符串不包含%d6
,而是包含NaN6
。
Now I know %d is used in C's sprinf, but afaik JavaScript nor Node has sprintf or equivalent function. 现在我知道%d用于C的sprinf,但是afaik JavaScript或Node也没有sprintf或等效功能。
I need %d6
in my string, so what can I do to prevent JS from automatically converting %d
(and others, like %f
) to NaN? 我的字符串中需要%d6
,那么如何防止JS自动将%d
(以及其他对象,如%f
)转换为NaN?
You cannot use toString method for your own purproses, because JS already has own function with that name. 您不能将toString方法用于您自己的目的,因为JS已经具有使用该名称的自己的函数。
What is the output of: 输出是什么:
ch = '%' + buffer[i].toString(16);
alert(ch);
alert(buffer[i]);
alert(buffer[i].toString(16));
The error is not in the code you pasted, if we do a quick test: 如果我们进行快速测试,则该错误不在您粘贴的代码中:
function test()
{
var stuff = 214;
var str = '', ch;
ch = '%' + stuff.toString(16);
alert(ch);
}
we see that what we want to be returned is in fact returned (%d6). 我们看到实际上要返回的是我们要返回的内容(%d6)。
NaN stands for not a number, are you sure what is in your buffer array is a number? NaN代表不是数字,您确定缓冲区数组中的数字是数字吗? Are you calling any other methods/functions on ch? 您还在ch上调用其他方法/函数吗?
Node's console.log() - the standard function for outputting - that I was using to print out the result behaves as printf and that is actually documented ( http://nodejs.org/docs/v0.4.11/api/stdio.html#console.log ). 我用来打印结果的Node的console.log()-用于输出的标准功能-表现为printf,并且实际上已记录在文档中( http://nodejs.org/docs/v0.4.11/api/stdio.html #console.log )。 Silly me, thanks averyone for leding me to the solution. 愚蠢的我,感谢averyone带领我提出解决方案。
sys.puts() prints the expected string. sys.puts()打印期望的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.