javascript 仅当value不等于0时才向字符串添加值

67up9zun  于 2023-05-12  发布在  Java
关注(0)|答案(4)|浏览(76)

如何在一个字符串的值不为0的情况下添加一个值?
例如value={”https://google.com?search=“+ query +“&lang=”+ language}
我只想在lang不为0时添加&lang=。
当language == 0时,预期答案:https://google.com?search=exampleQuery
当语言是另一回事时,例如。语言==“zh”:https://google.com?search=exampleQuery&lang=en
我尝试使用tenery操作符和可选链,但只允许可选链函数,而不是字符串。

wooyq4lh

wooyq4lh1#

您可以检查值并在必要时返回oly。

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)}`);
ars1skjm

ars1skjm2#

你想要的答案是:
value = { "https://google.com?search=" + query + (lang !== 0 ? "&lang="+language : null ) }
如果lang不为0,可以在cheek中添加if inline。

b4lqfgs4

b4lqfgs43#

value={("https://google.com?search=" + query + "&lang=" + language).replace('&lang=0', '')}
让我们试试这个:“replace”正在搜索&lang=0,如果成功,则仅替换为空字符串

  • 只有变量,我的意思是没有曲线括号在我的节点中工作
qkf9rpyu

qkf9rpyu4#

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));

相关问题