skip to Main Content

how can I add a value to a string only when the value is not 0?

e.g. value={"https://google.com?search=" + query + "&lang=" + language}

I want to add &lang= only if lang is not 0.

When language == 0, expected answer:
https://google.com?search=exampleQuery

When language is something else e.g. language == "en":
https://google.com?search=exampleQuery&lang=en

I tried using tenery operator and optional chaining but only allow to optional chain function, not string.

4

Answers


  1. You could check the value and return oly if necessary.

    const
        addNotZero = (key, value) => value ? `&${key}=${value}` : '';
        
    
    console.log(`https://google.com?search=x${addNotZero('lang', 0)}`);
    console.log(`https://google.com?search=x${addNotZero('lang', 1)}`);
    Login or Signup to reply.
  2. function x(path, langCode, number){
     if(number){
      return  path+='&lang='+langCode;
     }
    
     return path;
    }
    
     console.log(x('https://google.com?search=exampleQuery', 'en', 0));
    console.log(x('https://google.com?search=exampleQuery', 'en', 1));
    
    Login or Signup to reply.
  3. The answer you’re looking for is:

    value = { "https://google.com?search=" + query + (lang !== 0 ? "&lang="+language : null ) }

    You can add an if inline to cheek if lang is not 0.

    Login or Signup to reply.
  4. value={("https://google.com?search=" + query + "&lang=" + language).replace('&lang=0', '')}
    let’s try this: "replace" is searching &lang=0 if succesfull just replacing with empty string
    *with just variable, I mean without curve brackets is working in my node

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search