英文:
Add value to a string only if value is not equal to 0
问题
如何仅在值不为0时将值添加到字符串中?
例如,值={"https://google.com?search=" + query + "&lang=" + language}
我想仅在lang不为0时添加&lang=。
当language == 0 时,期望的答案:
https://google.com?search=exampleQuery
当language为其他值,例如 language == "en"时:
https://google.com?search=exampleQuery&lang=en
我尝试使用三元运算符和可选链接,但只允许可选链接函数,而不是字符串。
英文:
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.
答案1
得分: 2
You could check the value and return only 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)}`);
英文:
You could check the value and return oly if necessary.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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)}`);
<!-- end snippet -->
答案2
得分: 1
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 check if lang
is not 0.
英文:
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.
答案3
得分: 0
value={("https://google.com?search=" + query + "&lang=" + language).replace('&lang=0', '')}
让我们尝试这样做:"replace"正在搜索&lang=0
,如果成功,就用空字符串替换。
*我指的是在我的节点中,仅使用变量而不是花括号也可以工作
英文:
value={("https://google.com?search=" + query + "&lang=" + language).replace('&lang=0', '')}
<br>
let's try this: "replace" is searching &lang=0
if succesfull just replacing with empty string<br>
*with just variable, I mean without curve brackets is working in my node
答案4
得分: -1
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));
英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论