build url in javascript

To build a URL in JavaScript, you can concatenate the different parts of the URL using the + operator, and encode any special characters using encodeURIComponent. One important part of a URL is the query string, which you can build by creating an object with the different parameters and values, and then converting it into a string using Object.entries and map. Here's an example:

index.tsx
const baseUrl = 'https://example.com';
const path = '/resource';
const queryParams = {
  param1: 'value1',
  param2: 'value2',
};

const queryString = Object.entries(queryParams)
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  .join('&');

const url = `${baseUrl}${path}?${queryString}`;
console.log(url);
// Output: "https://example.com/resource?param1=value1&param2=value2"
414 chars
15 lines

In this example, we first define the base URL (baseUrl) and the path to the resource (path). Then we define an object with the query parameters (queryParams), which has two parameters with their respective values. We create the query string by mapping each key-value pair to a string in the format key=value, where both the key and the value are encoded using encodeURIComponent. Finally, we concatenate the different parts of the URL using +, with the query string separated by ?. The resulting URL is then printed to the console.

gistlibby LogSnag