2

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?

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

4 Comments

You are the man!!!! I am always confused how to deal with encoding and escaping.. thanks. :)
In this case, what is the difference between qs.escape and encodeURI?
@Kelvin: there is effectively no difference for this example. The node.js docs for querystring.escape(...) even note that the function exists primarily so that it can be overridden. Using encodeURI(...) should yield the same result.
escape("abcde 李") == "abcde%20%u674E" ... encodeURI("abcde 李") == "abcde%20%E6%9D%8E"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.