murvinlai
murvinlai

Reputation: 50375

How to encode arbitrary string for request in Node.js?

I have a string like that: "abcde 李". It can be any string with non latin characters.

I want to encode it to use in request, so it will be "abcde %E6%9D%8E" and can be used for http.request.

I have tried this:

str.toString("utf-8");

or

var buffer = new Buffer(str);
str = buffer.toString('utf-8');

but none of them work. what is the proper way to handle this?

Upvotes: 2

Views: 3470

Answers (1)

maerics
maerics

Reputation: 156612

That string is already UTF-8. It looks like you're trying to escape it for use in an HTTP query string, so try this:

var qs = require('querystring');
qs.escape('abcde 李'); // => 'abcde%20%E6%9D%8E'

Upvotes: 3

Related Questions