How can I URL encode a string in Node.js?

How can I URL encode a string in Node.js?

I have a string like this:

SELECT name FROM user WHERE uid = me()

Do I need to install an additional module for this, or is there a built-in way to handle URL encoding in Node.js? I already have the request module.

Try using the encodeURIComponent() method in Node.js You can use the built-in encodeURIComponent() function, which is a standard JavaScript method for URL encoding:

const str = "SELECT name FROM user WHERE uid = me()";
const encodedStr = encodeURIComponent(str);
console.log(encodedStr);

This will encode the string SELECT name FROM user WHERE uid = me() to SELECT name FROM user WHERE uid 3D 2028 29.

Node.js has a built-in module called querystring, which can also be used for URL encoding:

const querystring = require('querystring');
const str = "SELECT name FROM user WHERE uid = me()";
const encodedStr = querystring.escape(str);
console.log(encodedStr);
The querystring.escape() method encodes the string, and it works similarly to encodeURIComponent().

The url module in Node.js provides another way to handle URL encoding, especially when working with full URLs or query parameters:

const { URLSearchParams } = require('url');
const str = "SELECT name FROM user WHERE uid = me()";
const encodedStr = new URLSearchParams({ query: str }).toString();
console.log(encodedStr);

This method will give you a URL-encoded string as part of a query string (e.g., query=SELECT+name+FROM+user+WHERE+uid+3D+me 28 29).