0

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

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals or https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format would be my first two suggestions. – CBroe Mar 29 '22 at 12:04

6 Answers6

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))
Sascha Geier
  • 153
  • 11
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))
 
shutsman
  • 2,357
  • 1
  • 12
  • 23
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));
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
0

i guess if your object variables doesn't have a / for a first character, you can do this:

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

function path(obj, str = "") {
    let res = "";
    str.split("%").forEach((e) => {
        res += e && e[0] != "/" ? obj[e] : e;
    })
    return res;
}
Suolumi
  • 36
  • 4
0

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

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

const makePath = (obj, str) => {
    const items = str.match(/%.[a-zA-Z]+%/g);
    let newStr = str;

    for (const item of items) {
        newStr = newStr.replace(item, obj[item.replace(/%/g, '')]);
    }

    return encodeURI(newStr);
};

console.log(makePath(obj, str));
mstephen19
  • 1,733
  • 1
  • 5
  • 20
0
const makePath = (obj, str) => {    
 Object.keys(obj).reduce((acc, key) => acc.replace(%${key}%, encodeURI(obj[key])), 
 str)
 return str;
}
Jakub Kurdziel
  • 3,216
  • 2
  • 12
  • 22
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 30 '22 at 16:12