如何使JavaScript中所有单词的第一个字符大写?

如何使JavaScript中所有单词的第一个字符大写?,javascript,string,Javascript,String,我一直在寻找解决办法,但还没有找到 我有下面的字符串 1. hello 2. HELLO 3. hello_world 4. HELLO_WORLD 5. Hello World 我想将它们转换为以下内容: 1. Hello 2. Hello 3. HelloWorld 4. HelloWorld 5. HelloWorld 若字符串中并没有空格和下划线,那个么只需将大写字母放在第一位,其他所有字母则改为小写字母。如果单词由下划线或空格分隔,则每个单词的第一个字母应大写,并删除空格和下划线。

我一直在寻找解决办法,但还没有找到

我有下面的字符串

1. hello
2. HELLO
3. hello_world
4. HELLO_WORLD
5. Hello World
我想将它们转换为以下内容:

1. Hello
2. Hello
3. HelloWorld
4. HelloWorld
5. HelloWorld
若字符串中并没有空格和下划线,那个么只需将大写字母放在第一位,其他所有字母则改为小写字母。如果单词由下划线或空格分隔,则每个单词的第一个字母应大写,并删除空格和下划线。如何在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("");
}
函数toPascalCase(str){
var arr=str.split(/\s |/);
for(vari=0,l=arr.length;i1?arr[i].substr(1).toLowerCase():“”);
}
返回arr.join(“”);
}
,方法非常简单,在查找空格或下划线时将字符串放入数组中。然后循环遍历数组,第一个字母大写,其余字母小写…然后将标题大小写单词数组再次合并为一个字符串

function foo(str) {
    return $(str.split(/\s|_/)).map(function() {
        return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
    }).get().join("");
}
工作演示: (我在演示中使用了Nicks正则表达式)


编辑:代码的另一个版本-我用$.map()替换了map():


工作演示:

这里是一个正则表达式解决方案:

字符串的第一个小写字母:

 str = str.toLowerCase();
用大写字符替换单词中的所有
\uuu
和空格以及第一个字符:

 str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})

更新:减少步骤;)

说明:

/            // start of regex
 (?:         // starts a non capturing group
   _| |\b    // match underscore, space, or any other word boundary character 
             // (which in the end is only the beginning of the string ^)
  )          // end of group
 (           // start capturing group
  \w         // match word character
 )           // end of group
/g           // and of regex and search the whole string

捕获组的值在函数中可用为
p1
,整个表达式由函数的返回值替换。

的ES6/函数更新。与@NickCraver的答案一样,此函数将通过过滤多个空格/下划线来正确处理它们

const pascalWord=x=>x[0].toUpperCase()+x.slice(1).toLowerCase();
常量toPascalCase2=(str)=>(
str.split(/\s | uu/)
.filter(x=>x)
.map(pascalWord)
.加入(“”)
);
常数测试=[
“你好”,
“你好”,
“你好,世界”,
“你好,世界”,
“你好,世界”,
“你好,世界”,
“你好,世界”,
].map(toPascalCase2).join(“
”); 文件。编写(测试)var city=city.replace(//\s+/g',)//将所有空格替换为Single speace
city=city.replace(//\b\w/g,city=>city.toUpperCase())///speace-letter-convert-capital

@tvanfosson:如果有任何错误,您可以编辑。谢谢你,现在我将删除我的评论,因为它不再有意义了。为什么需要jQuery呢?另外,
.map()
是为jQuery对象而设计的,而不是常规数组。在这种情况下,请使用
$.map()
。。尽管在这里使用jQuery(除非已经包含它)不是一个好方法……而且这两种方法的效率都较低。@Nick是的,性能较低。但是,代码更小,可读性更强。如果OP在页面上使用jQuery,那么他应该不会介意这个解决方案。所以大家都是+1。但第一个答案是可以接受的。感谢这也将删除字符串上的所有空格或下划线
aakil费尔南德斯
将成为
aakil费尔南德斯
我这里有一些好的答案。所以大家都是+1。但第一个答案是可以接受的。谢谢这个解决方案是最好的,但是我更喜欢使用
//gi
并删除
str=str.toLowerCase()行。为什么
.filter(x=>x)
?@MikeChamberlain它过滤掉空白字符串
['Hello',''World']。filter(x=>x)=['Hello','World']
。也许有更好的方法,但这是我能想到的最实用的方法。然后在
map
中,你不必担心空的stringsAh,哥达。Yeah filter接受一个谓词,因此这里将
x
强制为布尔值,对于空字符串为
false
。也许
!!x
会更地道吗?@MikeChamberlain这里有一些做
过滤器的新奇方法:欢迎使用SO!虽然这可能回答了这个问题,但如果您稍微改进一下,它可能会更有用。请花些时间检查一下,并考虑添加一些关于代码的信息。
/            // start of regex
 (?:         // starts a non capturing group
   _| |\b    // match underscore, space, or any other word boundary character 
             // (which in the end is only the beginning of the string ^)
  )          // end of group
 (           // start capturing group
  \w         // match word character
 )           // end of group
/g           // and of regex and search the whole string