Search code examples
javascriptreactjsfrontendcypresstemplate-literals

Javascript: How to add an optional forward slash to a template literal


So I am trying to have two optional arguments and an optional forward slash. The reason I need an optional forward slash is because the base url is just localhost:3000/web/reserve not localhost:3000/web/reserve/. The default empty arguments are working as expected when passing nothing into webpageCheck however I can't get the optional (/) to work. If I did http://localhost:3000/web/reserve/${label}${count} it would fail when calling webpageCheck because there is no forward slash at the end. Does anyone know how to do this?

const web = {
        label: 'Hello',
        count: '10',
    };
    
const webpageCheck = (label = '', count = '') => {
     const optionalSlash = '/'
      cy.url().should(
         'eq',
         `http://localhost:3000/web/reserve${optionalSlash + label}${optionalSlash + count}`
        );
    };
    
 webpageCheck()

Solution

  • So, it sounds like the optionalSlash should be in the string before label or count, and if label or count is missing, we skip adding the optionalSlash for that variable. If that's true, you could do a simple ternary when constructing the string.

    http://localhost:3000/web/reserve${
      label ? optionalSlash + label : ''
      }${
      count ? optionalSlash + count : ''}`