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

580
Vistas
Is there a built-in javascript function similar to os.path.join?

Is there a built-in javascript (client-side) function that functions similarly to Node's path.join? I know I can join strings in the following manner:

['a', 'b'].join('/')

The problem is that if the strings already contain a leading/trailing "/", then they will not be joined correctly, e.g.:

['a/','b'].join('/')
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Use the path module. path.join is exactly what you're looking for. From the docs:

path.join([path1][, path2][, ...])# Join all arguments together and normalize the resulting path.

Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.

Example:

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns
'/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// throws exception
TypeError: Arguments to path.join must be strings

Edit:

I assumed here that you're using server-side Javascript like node.js. If you want to use it in the browser, you can use path-browserify.

over 4 years ago · Santiago Trujillo Denunciar

0

Building on @Berty's reply, this ES6 variant preserves all leading slashes, to work with protocol relative url's (like //stackoverflow.com), and also ignores any empty parts:

build_path = (...args) => {
  return args.map((part, i) => {
    if (i === 0) {
      return part.trim().replace(/[\/]*$/g, '')
    } else {
      return part.trim().replace(/(^[\/]*|[\/]*$)/g, '')
    }
  }).filter(x=>x.length).join('/')
}
  • build_path("http://google.com/", "my", "path") will return "http://google.com/my/path"
  • build_path("//a", "", "/", "/b/") will return "//a/b"
  • build_path() will return ""

Note that this regex strips trailing slashes. Sometimes a trailing slash carries semantic meaning (e.g. denoting a directory rather than a file), and that distinction will be lost here.

over 4 years ago · Santiago Trujillo Denunciar

0

There isn't currently a built-in that will perform a join while preventing duplicate separators. If you want concise, I'd just write your own:

function pathJoin(parts, sep){
   var separator = sep || '/';
   var replace   = new RegExp(separator+'{1,}', 'g');
   return parts.join(separator).replace(replace, separator);
}

var path = pathJoin(['a/', 'b', 'c//'])
over 4 years ago · Santiago Trujillo 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