如何使 JavaScript 中所有单词的第一个字符大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4478227/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make first character uppercase of all words in JavaScript?
提问by Awan
I have searched for solution but did not find yet.
我已经搜索了解决方案,但还没有找到。
I have the following string.
我有以下字符串。
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
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.
如果字符串中没有空格和下划线,则先大写,其他所有小写。如果单词由下划线或空格分隔,则每个单词的第一个字母大写并删除空格和下划线。我怎样才能在 JavaScript 中做到这一点。
Thanks
谢谢
回答by Felix Kling
Here is a regex solution:
这是一个正则表达式解决方案:
First lowercase the string:
首先小写字符串:
 str = str.toLowerCase();
Replace all _and spaces and first characters in a word with upper case character:
_用大写字符替换单词中的所有和空格和第一个字符:
 str = str.replace(/(?:_| |\b)(\w)/g, function(str, p1) { return p1.toUpperCase()})
Update:Less steps ;)
更新:更少的步骤;)
Explanation:
解释:
/            // 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
The value of the capturing group is available as p1in the function, and the wholeexpression is replaced by the return value of the function.
捕获组的值p1在函数中可用,整个表达式由函数的返回值替换。
回答by Nick Craver
You could do something like this:
你可以这样做:
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("");
}
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.
你可以在这里测试它,方法很简单,.split()找到空格或下划线时将字符串转换为数组。然后循环遍历数组,将第一个字母大写,将其余字母小写……然后将标题大小写的单词数组和.join()它再次组合成一个字符串。
回答by ?ime Vidas
function foo(str) {
    return $(str.split(/\s|_/)).map(function() {
        return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
    }).get().join("");
}
Working demo:http://jsfiddle.net/KSJe3/3/(I used Nicks regular expression in the demo)
工作演示:http : //jsfiddle.net/KSJe3/3/(我在演示中使用了 Nicks 正则表达式)
Edit:Another version of the code - I replaced map() with $.map():
编辑:代码的另一个版本 - 我用 $.map() 替换了 map():
function foo(str) {
    return $.map(str.split(/\s|_/), function(word) {
        return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
    }).join("");
}
Working demo:http://jsfiddle.net/KSJe3/4/
工作演示:http : //jsfiddle.net/KSJe3/4/
回答by icc97
An ES6 / functional update of @NickCraver's answer. As with @NickCraver's answer this function will handle multiple spaces / underscores properly by filtering them out.
@NickCraver's answer的 ES6 / 功能更新。与@NickCraver 的回答一样,此函数将通过过滤掉多个空格/下划线来正确处理它们。
const pascalWord = x => x[0].toUpperCase() + x.slice(1).toLowerCase();
const toPascalCase2 = (str) => (
  str.split(/\s|_/)
    .filter(x => x)
    .map(pascalWord)
    .join('')
);
const tests = [
'hello',
'HELLO',
'hello_world',
'HELLO_WORLD',
'Hello World',
'HELLO__WORLD__',
'Hello   World_',
].map(toPascalCase2).join('<br>');
document.write(tests);
回答by rambabu mikkili
var city = city.replace(/\s+/g,' ') //replace all spaceses to singele speace city = city.replace(/\b\w/g,city => city .toUpperCase()) //after speace letter convert capital
var city = city.replace(/\s+/g,' ') //将所有空格替换为单个空格 city = city.replace(/\b\w/g,city => city .toUpperCase()) //after空格字母转换大写

