如何在JavaScript中使所有单词的第一个字符大写? [英] How to make first character uppercase of all words in JavaScript?

查看:102
本文介绍了如何在JavaScript中使所有单词的第一个字符大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了解决方案但尚未找到。

I have searched for solution but did not find yet.

我有以下字符串。

1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World

我想将它们转换为以下内容:

I want to convert them to following:

1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld

如果字符串中没有空格和下划线,则首先是大写,而所有其他都是小写。如果单词由下划线或空格分隔,则每个单词的大写第一个字母,并删除空格和下划线。我怎么能用JavaScript做这件事。

If there is No space and underscore in string just uppercase first and all others to lowercase. If words are separated by underscore or space then Uppercase first letter of each word and remove space and underscore. How can I do this in JavaScript.

谢谢

推荐答案

你可以做这样的事情:

function toPascalCase(str) {
    var arr = str.split(/\s|_/);
    for(var i=0,l=arr.length; i<l; i++) {
        arr[i] = arr[i].substr(0,1).toUpperCase() + 
                 (arr[i].length > 1 ? arr[i].substr(1).toLowerCase() : "");
    }
    return arr.join("");
}

你可以在这里测试一下,方法非常简单, .split() 分解为查找空格或下划线时的数组。然后循环遍历数组,上面包装第一个字母,下面包括其余部分...然后取这个标题 - 单词数组和 .join() 它再次组合成一个字符串。

You can test it out here, the approach is pretty simple, .split() the string into an array when finding either whitespace or an underscore. Then loop through the array, upper-casing the first letter, lower-casing the rest...then take that array of title-case words and .join() it together into one string again.

这篇关于如何在JavaScript中使所有单词的第一个字符大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆