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

146
Vistas
Check if string start with an Array of strings

I have an array of strings :
listOfTypes = ['blogPost', 'work']

And I have a routeName routeName = blogPost-slug or routeName = blogPost;

When routeName contains = blogPost I want to return string "page".
If routeName start with string- (example: blogPost-), I want to return the type (from listOfTypes)

I made a forEach function that works. Only, I get several results (it's normal) when I only want one (if it is present in the array, then I return either the type or page)

listOfTypes = ['blogPost', 'work'];

// routeName is retrieved dynamically. This is for example, "blogPost" or "blogPost-slug" or "work-slug"

listOfTypes.forEach(type => {
      // Check if route name starts with type + "-" because it's separator with subroute 
      // (/blogPost is a page, /blogPost-slug is a blogPost so check for blogPost-)

      if(routeName.startsWith(type + '-')) {
        return console.log(type);
      } else {
        return console.log('page');
      }
    });

// result: 'blogPost' and 'page'
// expected result: 'blogPost'

How can I do this and only get either the type or "page" if it doesn't match?

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Using Array#find:

const listOfTypes = ['blogPost', 'work'];

const getType = route => 
  listOfTypes.find(type => route.startsWith(`${type}-`)) ?? 'page';

console.log( getType('blogPost') );
console.log( getType('blogPost-slug') );
console.log( getType('work-slug') );

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