在 JavaScript 中检查字符串中的字符是否大写
在本教程中,我们将演示如何检查包含各种字符的给定字符串是否具有大写格式的所有字符。
在 JavaScript 中,没有内置函数来检查给定字符串中的每个字符是否为大写格式。所以,我们必须实现我们的函数。
在这里,我们将创建一个名为 isUpperCase()
的函数,一个匿名箭头函数,告诉我们字符串中的所有字符是否都是大写的。如果是这样,它会在控制台中打印一条消息。
如果字符串中的任何字符不是大写格式,它将在控制台窗口上打印它们。isUpperCase()
函数将采用单个参数 providedStr
作为输入。
在编写 isUpperCase()
函数的逻辑之前,让我们首先声明一些变量。首先,我们将声明两个字符串变量,str_1
和 str_2
,其中包含一些字符串值。
我们将把这两个变量作为检查大写格式的参数传递给 isUpperCase()
函数。
代码片段:
let str_1 = "AB% ^M";
let str_2 = "IO(|12c";
let allUpperCase = true;
let isUpperCase = providedStr => {
for(i in providedStr){
if(providedStr[i] !== providedStr[i].toUpperCase()){
allUpperCase = false;
console.log(`Letter ${providedStr[i]} is not uppercase.`);
}
}
if(allUpperCase){
console.log("All characters in a given string are uppercase...")
}
}
isUpperCase(str_1);
isUpperCase(str_2);
然后,我们将声明另一个名为 allUpperCase
的变量,一个布尔变量。默认情况下,我们会将其值分配给 True。
我们假设提供的字符串中的所有字符都已经是大写格式。
在 isUpperCase()
函数中,我们将在 providedStr
变量上应用 for...in
循环。在每次迭代中,这个 for...in
循环将为我们提供字符串中每个字符的索引 i
。
现在我们有了字符串中单个字符的索引,我们可以获取这个 i
变量并使用 providedStr[i]
访问该字符。在这里,我们将使用 providedStr[i]
从字符串中获取字符,然后将其与 providedStr[i].toUpperCase()
进行比较。
toUpperCase()
函数将使该字符变为大写。所以,如果字符已经是大写格式,它不会做任何事情。
如果字符已经是大写格式,则不会执行 if
语句。如果字符串中的任何字符不是大写格式,程序将进入 if
语句。
它将使变量 allUpperCase
为假,这意味着我们找到了一个字符,而不是大写格式,然后我们将在控制台窗口上打印该字符。
遍历字符串中的所有字符后,我们将执行条件检查以了解 allUpperCase
变量中的值是否为真。如果为 true
,则字符串中的所有字符均为大写格式。
输出:
在这里,因为我们的第一个字符串变量 str_1
包含所有大写值 AB% ^M
。因此,它所打印的所有字符都是大写的。
请注意,此字符串中也有一个空格字符。在第二个字符串变量 str_2
中,从所有字符 IO(|12c
中,我们只有字符 c
,它不是大写格式,所以它在控制台窗口上打印这个字符。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。