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

145
Views
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 answers
Answer question

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 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!