编写一个函数,它接受一个字符串和 returns 一个新字符串,其中只有大写字母传递给该字符串
write a function which accepts a string and returns a new string with only the capital letters passed to the string
所以我实际上在 rithm school 的 javascript 教程中遇到了这个问题(到目前为止非常好):编写一个名为 onlyCapitalLetters 的函数,它接受一个字符串和 returns只有大写字母传递给字符串的新字符串。这是请求的输出:
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
你已经得到了这个解决方案,但是它使用了他们之前没有讨论过的 .charCodeAt() 方法,而且看起来也很复杂。现在我正在阅读大量与它相关的文档,但仍然无法挖掘它。
在深入研究他们的解决方案之前,我自己尝试了一些其他方法,这些方法基于本教程中已经介绍的内容。
算术学校的解法:
function onlyCapitalLetters(str){
var newStr = '';
for(var i = 0; i < str.length; i++){
if(str[i].charCodeAt(0) < 91 && str[i].charCodeAt(0) > 64 ){
newStr += str[i];
}
}
return newStr;
}
我的尝试:
function onlyCapitalLetters(string) {
var newString = '';
for(i=0;i<string.length;i++) {
if(string[i] === string[i].toUpperCase) {
} newString += string[i];
}
return newString;
}
虽然,当我抛出一个字符串作为参数时,例如
onlyCapitalLetters('TbRnY OnUmT');
它按原样给了我字符串,而不是一个新的、只有大写的字符串。
"TbRnY OnUmT"
有没有办法,在我尝试过的这个简化方向上,实现这个功能?此外,有没有人对这个 charCodeAt 及其整个解决方案有一些了解?这是我的第一个 post,非常感谢您的帮助!
我会使用 regex
。
/[A-Z]/g
匹配所有大写字母。
join('')
将匹配的字符数组转换回字符串。
function onlyCapitalLetters(input){
let op = input.match(/[A-Z]/g) || ''
if(op) op = op.join('')
console.log(op)
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING")
onlyCapitalLetters('TbRnY OnUmT');
关于您的尝试,您几乎成功了!你的错误是:
toUpperCase
应该是toUpperCase()
,因为这是必须应用的方法
- 删除空的
{}
块;这将防止以下语句仅在 if
语句为真时执行;您还可以在 {}
块 内移动串联
修改后的版本如下:
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase())
newString += string[i];
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("TesT"));
console.log(onlyCapital("TbRnY OnUmT"));
但是,这对像 "abc#@" 这样的字符串不起作用,因为将 toUpperCase()
应用于特殊字符,将 return 相同的字符,并且 if 语句将是true,导致串联。这就是他们使用 charCodeAt(0)
的原因。 This function in javascript returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. For ASCII characters, it means it will return a number between 0 and 127. What can we do with this number? We can compare it with other numbers (take a look at the ASCII table here) 并测试它是否是一个有效的字母。查看 table,我们可以看到:
- A是65
- Z 为 90
- a 是 97
- z 为 122
根据以上信息,我们可以创建另一个名为 isLetter
的函数,该函数将测试给定字符是否为有效字母。如何?测试我们角色的代码是在 A 和 Z 之间还是在 a 和 z 之间。但是,因为我们无论如何都不需要较小的字母,所以我们可以只测试 [A, Z]。结合上面的代码,我们将得到:
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90)
}
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (isUppercaseLetter(string[i])) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("EVERYTHING"));
console.log(onlyCapital("TbRnY OnUmT"));
console.log(onlyCapital("S@P#E!C#I?A;L"));
奖金:
我将使用 filter
lambda 函数来完成。首先,我们将字符串转换为 char 数组,然后只保留大写字符。您可以详细了解 reduce 的工作原理 here. Another method using functionals would be with reduce
. You can take a look how reduce works here。基本上我使用 split
将字符串转换为 char 数组,然后对于每个字符,我要么将其添加到部分结果中,要么只保留部分结果。最后,我应该有我的字符串。
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90);
}
function onlyCapitalWithFilter(s) {
return s.split('').filter(c => isUppercaseLetter(c)).join('');
}
function onlyCapitalWithReduce(s) {
return s.split('').reduce((a, c) => isUppercaseLetter(c) ? a + c : a, '');
}
console.log(onlyCapitalWithFilter("nothing"));
console.log(onlyCapitalWithFilter("TesT"));
console.log(onlyCapitalWithFilter("TbRnY OnUmT"));
console.log(onlyCapitalWithFilter("S@P#E!C#I?A;L"));
console.log(onlyCapitalWithReduce("nothing"));
console.log(onlyCapitalWithReduce("TesT"));
console.log(onlyCapitalWithReduce("TbRnY OnUmT"));
console.log(onlyCapitalWithReduce("S@P#E!C#I?A;L"));
function onlyCapitalLetters(string) {
// prime the function response.
let response = "";
// match all groups of uppercase letters.
let result = string.match(/([A-Z]+)/g);
// check for matches.
if( result != null && result.length ) {
// remove first element of match result (which returns the original string.
result.unshift();
// join the array into a string with an empty "separator".
response = result.join('');
}
console.log(response);
return response;
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
onlyCapitalLetters('TbRnY OnUmT'); // "TRYOUT"
要修复您的代码,请使用 toUpperCase() 包括括号并连接 if 语句中的字符串:
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
请注意,正如 @CodeManiac 指出的那样,此函数不会从字符串中删除特殊字符。使用 nothing@#
将 return @#
例如
function onlyCapitalLetters(string) {
var newString = '';
for (let i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
console.log(onlyCapitalLetters('nothing@#'));
另一种选择是将非大写字符或空白字符替换为空字符串:
function onlyCapitalLetters(string) {
return string.replace(/[^A-Z\s]+/g, '');
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
这是一个紧凑的解决方案
var string = "ABCefgGHaI";
首先替换除字母以外的所有字符
string.replace(/[^a-z]/gi, '')
(string.split('').filter((item)=>{return item == item.toUpperCase()})).join("")
您可以通过拆分单词并仅过滤大写的单词并重新加入它们来做到这一点:)
另一个选项使用 array destructuring
作为函数参数。
const onlyCapitalLetters = ([...myarr] = e) => myarr.filter(el => el === el.toUpperCase()).join('');
console.log(onlyCapitalLetters("Amazing"));
console.log(onlyCapitalLetters("nothing"));
console.log(onlyCapitalLetters("EVERYTHING"));
所以我实际上在 rithm school 的 javascript 教程中遇到了这个问题(到目前为止非常好):编写一个名为 onlyCapitalLetters 的函数,它接受一个字符串和 returns只有大写字母传递给字符串的新字符串。这是请求的输出:
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
你已经得到了这个解决方案,但是它使用了他们之前没有讨论过的 .charCodeAt() 方法,而且看起来也很复杂。现在我正在阅读大量与它相关的文档,但仍然无法挖掘它。
在深入研究他们的解决方案之前,我自己尝试了一些其他方法,这些方法基于本教程中已经介绍的内容。
算术学校的解法:
function onlyCapitalLetters(str){
var newStr = '';
for(var i = 0; i < str.length; i++){
if(str[i].charCodeAt(0) < 91 && str[i].charCodeAt(0) > 64 ){
newStr += str[i];
}
}
return newStr;
}
我的尝试:
function onlyCapitalLetters(string) {
var newString = '';
for(i=0;i<string.length;i++) {
if(string[i] === string[i].toUpperCase) {
} newString += string[i];
}
return newString;
}
虽然,当我抛出一个字符串作为参数时,例如
onlyCapitalLetters('TbRnY OnUmT');
它按原样给了我字符串,而不是一个新的、只有大写的字符串。
"TbRnY OnUmT"
有没有办法,在我尝试过的这个简化方向上,实现这个功能?此外,有没有人对这个 charCodeAt 及其整个解决方案有一些了解?这是我的第一个 post,非常感谢您的帮助!
我会使用 regex
。
/[A-Z]/g
匹配所有大写字母。
join('')
将匹配的字符数组转换回字符串。
function onlyCapitalLetters(input){
let op = input.match(/[A-Z]/g) || ''
if(op) op = op.join('')
console.log(op)
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING")
onlyCapitalLetters('TbRnY OnUmT');
关于您的尝试,您几乎成功了!你的错误是:
toUpperCase
应该是toUpperCase()
,因为这是必须应用的方法- 删除空的
{}
块;这将防止以下语句仅在if
语句为真时执行;您还可以在{}
块 内移动串联
修改后的版本如下:
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase())
newString += string[i];
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("TesT"));
console.log(onlyCapital("TbRnY OnUmT"));
但是,这对像 "abc#@" 这样的字符串不起作用,因为将 toUpperCase()
应用于特殊字符,将 return 相同的字符,并且 if 语句将是true,导致串联。这就是他们使用 charCodeAt(0)
的原因。 This function in javascript returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. For ASCII characters, it means it will return a number between 0 and 127. What can we do with this number? We can compare it with other numbers (take a look at the ASCII table here) 并测试它是否是一个有效的字母。查看 table,我们可以看到:
- A是65
- Z 为 90
- a 是 97
- z 为 122
根据以上信息,我们可以创建另一个名为 isLetter
的函数,该函数将测试给定字符是否为有效字母。如何?测试我们角色的代码是在 A 和 Z 之间还是在 a 和 z 之间。但是,因为我们无论如何都不需要较小的字母,所以我们可以只测试 [A, Z]。结合上面的代码,我们将得到:
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90)
}
function onlyCapital(string) {
var newString = '';
for (i = 0; i < string.length; i++) {
if (isUppercaseLetter(string[i])) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapital("nothing"));
console.log(onlyCapital("EVERYTHING"));
console.log(onlyCapital("TbRnY OnUmT"));
console.log(onlyCapital("S@P#E!C#I?A;L"));
奖金:
我将使用 filter
lambda 函数来完成。首先,我们将字符串转换为 char 数组,然后只保留大写字符。您可以详细了解 reduce 的工作原理 here. Another method using functionals would be with reduce
. You can take a look how reduce works here。基本上我使用 split
将字符串转换为 char 数组,然后对于每个字符,我要么将其添加到部分结果中,要么只保留部分结果。最后,我应该有我的字符串。
function isUppercaseLetter(c) {
return (c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90);
}
function onlyCapitalWithFilter(s) {
return s.split('').filter(c => isUppercaseLetter(c)).join('');
}
function onlyCapitalWithReduce(s) {
return s.split('').reduce((a, c) => isUppercaseLetter(c) ? a + c : a, '');
}
console.log(onlyCapitalWithFilter("nothing"));
console.log(onlyCapitalWithFilter("TesT"));
console.log(onlyCapitalWithFilter("TbRnY OnUmT"));
console.log(onlyCapitalWithFilter("S@P#E!C#I?A;L"));
console.log(onlyCapitalWithReduce("nothing"));
console.log(onlyCapitalWithReduce("TesT"));
console.log(onlyCapitalWithReduce("TbRnY OnUmT"));
console.log(onlyCapitalWithReduce("S@P#E!C#I?A;L"));
function onlyCapitalLetters(string) {
// prime the function response.
let response = "";
// match all groups of uppercase letters.
let result = string.match(/([A-Z]+)/g);
// check for matches.
if( result != null && result.length ) {
// remove first element of match result (which returns the original string.
result.unshift();
// join the array into a string with an empty "separator".
response = result.join('');
}
console.log(response);
return response;
}
onlyCapitalLetters("Amazing") // "A"
onlyCapitalLetters("nothing") // ""
onlyCapitalLetters("EVERYTHING") // "EVERYTHING"
onlyCapitalLetters('TbRnY OnUmT'); // "TRYOUT"
要修复您的代码,请使用 toUpperCase() 包括括号并连接 if 语句中的字符串:
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
请注意,正如 @CodeManiac 指出的那样,此函数不会从字符串中删除特殊字符。使用 nothing@#
将 return @#
例如
function onlyCapitalLetters(string) {
var newString = '';
for (let i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
}
return newString;
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
console.log(onlyCapitalLetters('nothing@#'));
另一种选择是将非大写字符或空白字符替换为空字符串:
function onlyCapitalLetters(string) {
return string.replace(/[^A-Z\s]+/g, '');
}
console.log(onlyCapitalLetters('TbRnY OnUmT'));
这是一个紧凑的解决方案
var string = "ABCefgGHaI";
首先替换除字母以外的所有字符
string.replace(/[^a-z]/gi, '')
(string.split('').filter((item)=>{return item == item.toUpperCase()})).join("")
您可以通过拆分单词并仅过滤大写的单词并重新加入它们来做到这一点:)
另一个选项使用 array destructuring
作为函数参数。
const onlyCapitalLetters = ([...myarr] = e) => myarr.filter(el => el === el.toUpperCase()).join('');
console.log(onlyCapitalLetters("Amazing"));
console.log(onlyCapitalLetters("nothing"));
console.log(onlyCapitalLetters("EVERYTHING"));