Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 : ''}`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading