Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda