在 JavaScript 中将字符串转换为标题大小写
在 JavaScript 中有 toLowerCase()
、toUpperCase()
和 capitalize()
属性来与字符串交互。但是没有明确的属性可以将句子或字符串转换为标题大小写。
因此,在下面的示例中,我们将看到如何快速有效地完成任务。在这里,我们将讨论将字符串转换为标题大小写的 3 种方法。
在第一种情况下,我们将用空格分割字符串单词,然后启动一个循环工作来抓取每个要转换的单词。以下示例将使用 map
执行。
我们还将在我们的地图中使用 replace
方法。
在处理每个字符串单词之前,我们必须逐字执行转换。在这种情况下,我们将通过空格使用 split()
方法,单词将被收集为一个数组。
此外,在此之前,我们将使用 toLowerCase()
属性将所有字符转换为通用格式。
在下一步中,我们将考虑每个数组元素的一个单词来对初始字符进行 toUpperCase
操作,并对后面的字符进行切片。
因此将完全转换字符串,最后,我们将加入
它们并将它们打印为单个字符串
。
代码片段:
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
}
console.log(titleCase("hello pumpkin pumpkin you my hello honey bunny!"));
输出:
我们的实例将从字符串中获取每个数组元素并在此处执行转换操作。
与前面的示例类似,我们将选择要转换为大写的初始字符并对其余部分进行分割。
代码片段:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(' ');
}
console.log(titleCase("you gone MAD?"));
输出:
如你所见,在映射每个 word
后,我们使用 charAt()
定位第一个字母,并将该单词与以下字符合并。
在这种情况下,我们将定位每个单词的首字母并将它们转换为大写。在转换时,我们将使用 replace()
方法并将更改后的字符设置为原始位置。
代码片段:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
console.log(titleCase("i'm just appreciating hoho!"));
输出:
.
相关文章
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 事件。