从字符串中仅提取大写字母 - javascript

时间:2020-12-22 06:18:24

标签: javascript arrays string

 function onlyCapitalLetters (str)  

 { 

let newStr = "";

for (let i = 0; i < str.length; i ++) {
    if (str[i].includes("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
        newStr += str[i];
       
    }
}
return newStr;
}

onlyCapitalLetters("AMazing"); // should get AM

嗨,我正在尝试编写一个函数,它将返回一个只有大写字母的新字符串。当我尝试运行此函数时,我看不到任何输出。请帮忙!!!

4 个答案:

答案 0 :(得分:1)

Include 要求包含在提供的字符串中的所有内容。改用正则表达式

function onlyCapitalLetters (str) { 
  let newStr = "";

  for (let i = 0; i < str.length; i++) {
      if (str[i].match(/[A-Z]/)) {
          newStr += str[i];
      }
   }
   return newStr;
}


console.log(onlyCapitalLetters("AMazing")); // should get AM

你可以把这个函数写成这样

const capital = (str) => str.split('').filter(a => a.match(/[A-Z]/)).join('')

console.log(capital("AMazinG"))

答案 1 :(得分:1)

在实践中,您可能会在这里使用正则表达式方法:

function onlyCapitalLetters (str) {
    return str.replace(/[^A-Z]+/g, "");
}

console.log(onlyCapitalLetters("AMazing")); // should get AM

答案 2 :(得分:0)

字母串 (uppercaseLetters) 应包括当前字母 (str[i]),而不是相反:

function onlyCapitalLetters(str) {
  let newStr = "";
  
  const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  for (let i = 0; i < str.length; i++) {
    if (uppercaseLetters.includes(str[i])) {
      newStr += str[i];
    }
  }
  
  return newStr;
}

console.log(onlyCapitalLetters("AMazing")); // should get AM

更好的选择是使用 String.match() 查找所有大写字母。 match 方法返回一个找到的字母数组,如果没有找到则返回 null,因此我们需要使用一个空数组作为后备。用空字符串连接结果数组。

function onlyCapitalLetters(str) {
  return (str.match(/[A-Z]/g) || []).join('');
}

console.log(onlyCapitalLetters("AMazing")); // should get AM

答案 3 :(得分:0)

String.Includes() 检查字符串中的所有字符。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

您也可以使用 ASCII 码作为字符来验证它是否是大写字母。

function onlyCapitalLetters (str) { 
 let newStr = "";

    for (let i = 0; i < str.length; i++) {
      if (str[i].charCodeAt(0) >= 65 && str[i].charCodeAt(0) <= 90) {
          newStr += str[i];
       }
    }
  return newStr;
}

console.log(onlyCapitalLetters("AMazing"));
相关问题