How do I URl encode something in Node.js?

05/05/2020 11:00:02

I want to URL encode this:

SELECT name FROM user WHERE uid = me() 

Do I have to download a module for this? I already have the request module.

Verified Answer (589 Votes)

07/02/2011 04:12:07

You can use JavaScript's encodeURIComponent:

encodeURIComponent('select * from table where i()')
589

Answer #2 (125 Votes)

07/03/2011 04:56:21

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'
125

Answer #3 (47 Votes)

02/10/2014 02:57:01

Use the escape function of querystring. It generates a URL safe string.

var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
console.log(escaped_str);
// prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'
47
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.