gpt4 book ai didi

javascript - 如何从字符串中只选择大写字符?

转载 作者:行者123 更新时间:2023-11-30 08:18:59 24 4
gpt4 key购买 nike

我尝试借助函数和 for 循环从字符串中选择大写字符,但我不知道该怎么做 我尝试使用 toUpperCase,正如您在代码中看到的那样,但它不起作用知道我该怎么做吗?

function onlyCapitalLetters(cap){
var string = "";
for(var i = 0; i < cap.length; i++){
if(cap[i] === cap.toUpperCase()){
string += cap[i];
}
}
return string;
}

onlyCapitalLetters("Apple");

最佳答案

您可以使用 String.prototype.match 尝试正则表达式仅返回大写字母:

function onlyCapitalLetters(cap){
return cap.match(/[A-Z]/g, "").join(''); // join the array to return a string
}

console.log(onlyCapitalLetters("Apple"));
console.log(onlyCapitalLetters("BUTTerfly"));
console.log(onlyCapitalLetters("LION"));

关于javascript - 如何从字符串中只选择大写字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57146135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com