Javascript: escape %d in string
I've got the following code in 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.
Now I know %d is used in C's sprinf, but afaik JavaScript nor Node has sprintf or equivalent function.
I need %d6
in my string, so what can I do to prevent JS from automatically converting %d
(and others, like %f
) to NaN?
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).
NaN stands for not a number, are you sure what is in your buffer array is a number? Are you calling any other methods/functions on ch?
You cannot use toString method for your own purproses, because JS already has own function with that name.
- Update firefox to newest version. Also make sure you are using firefox.
- I tested and your solution should work. Please alert() everything.
What is the output of:
ch = '%' + buffer[i].toString(16);
alert(ch);
alert(buffer[i]);
alert(buffer[i].toString(16));
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). Silly me, thanks averyone for leding me to the solution.
sys.puts() prints the expected string.
精彩评论