Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Iinsert values into url

I have a function which receives an object and a string. How can I nicely put values from an object into a string

const str = "/api/items/%id%/%name%";

let obj = { id  : 20, name: 'John Dow'};

function path(obj, str){ 
 let res = //some code 
 return res 
}

the function should return "/api/items/20/John%20Dow"

does not come up with a good solution. help me please

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The following function will do the trick:

const str = "/api/items/%id%/%name%";

let obj = { id  : 20, name: 'John Dow'};

function path(obj, str){ 
 for(const [key, value] of Object.entries(obj)) {
    str = str.replace(`%${key}%`, encodeURI(value))
 }
 return str; 
}

console.log(path(obj, str))
about 4 years ago · Juan Pablo Isaza Report

0

use template string with encodeURI method

let obj = { id  : 20, name: 'John Dow'};

const apiItemsPath = ({id, name}) => `/api/items/${id}/${encodeURI(name)}`

console.log(apiItemsPath(obj))
 

about 4 years ago · Juan Pablo Isaza Report

0

you can use :

  • Object.keys to iterate on object property
  • string.replace to replace element in your string
  • encodeUri to change special character to url encoded character

const str = "/api/items/%id%/%name%";

let obj = {
  id: 20,
  name: 'John Dow'
};

function path(obj, str) {
  let res = str;
  Object.keys(obj).forEach(key => {
    res = res.replace(`%${key}%`, encodeURI(obj[key]));
  });
  return res;
}

console.log(path(obj, str));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!