如何使用 JavaScript 将字符串中每个单词的第一个字母大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32589197/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:55:42  来源:igfitidea点击:

How to capitalize the first letter of each word in a string using JavaScript?

javascriptstringtitle-case

提问by slurrr

I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).

我正在尝试编写一个函数,将字符串中每个单词的第一个字母大写(将字符串转换为标题大小写)。

For instance, when the input is "I'm a little tea pot", I expect "I'm A Little Tea Pot"to be the output. However, the function returns "i'm a little tea pot".

例如,当输入是 时"I'm a little tea pot",我希望"I'm A Little Tea Pot"是输出。但是,该函数返回"i'm a little tea pot"

This is my code:

这是我的代码:

function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");

  for (var i = 0; i < splitStr.length; i++) {
    if (splitStr.length[i] < splitStr.length) {
      splitStr[i].charAt(0).toUpperCase();
    }

    str = splitStr.join(" ");
  }

  return str;
}

console.log(titleCase("I'm a little tea pot"));

回答by somethinghere

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

您不会再次将更改分配给数组,因此您的所有努力都是徒劳的。尝试这个:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));

回答by Marcos Pérez Gude

You are making complex a very easy thing. You can add this in your CSS:

你让复杂变得很容易。你可以在你的 CSS 中添加这个:

 .capitalize {
    text-transform: capitalize;   
  }

In javascript, you can add the class to an element

在javascript中,您可以将类添加到元素

 document.getElementById("element").className="capitalize";

回答by Steve Brush

ES6 version:

ES6版本:

const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);

回答by waqas

If you can use thirdparty library then lodash has a helper function for you.

如果您可以使用第三方库,那么 lodash 为您提供了一个辅助功能。

https://lodash.com/docs/4.17.3#startCase

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>

回答by nimeresam

I think this way should be faster; cause it doesn't split string and join it again; just using regex.

我认为这种方式应该更快;因为它不会拆分字符串并再次加入它;只是使用正则表达式。

var str = text.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());

Explanation:

说明

  1. (^\w{1}): match first char of string
  2. |: or
  3. (\s{1}\w{1}): match one char that came after one space
  4. g: match all
  5. match => match.toUpperCase(): replace with can take function, so; replace match with upper case match
  1. (^\w{1}): 匹配字符串的第一个字符
  2. |: 或者
  3. (\s{1}\w{1}): 匹配一个空格后的字符
  4. g: 全部匹配
  5. match => match.toUpperCase(): 替换为 can take 函数,所以;用大写匹配替换匹配

回答by Anshuman Singh

in ES6 one line answer using arrow function

在 ES6 中使用箭头函数的一行答案

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')

回答by Arthur Clemens

ES2015 version:

ES2015版本:

const titleCase = title => title
    .split(/ /g).map(word => 
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join("");

回答by Hyman Giffin

-

——

You could simply use a regular expression function to change the capitalization of each letter. With V8 JIST optimizations, this should prove to be the fast and memory efficient.

您可以简单地使用正则表达式函数来更改每个字母的大小写。使用 V8 JIST 优化,这应该被证明是快速和内存高效的。

// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})

Or, as a function:

或者,作为一个函数:

// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
    var charCode = x.charCodeAt(0);
    return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
    return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}

According to this benchmark, the code is over 33% faster than the next best solution in Chrome.

根据这个基准,代码比 Chrome 中的下一个最佳解决方案快 33% 以上。



<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
    "use strict"
    var fromCode = String.fromCharCode;
    function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
    (input.oninput = function(){
      output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
    })();
})();
</script>

回答by Charlie OConor

text-transform: capitalize;

Css has got it :)

CSS 已经搞定了 :)

回答by chickens

Shortest One Liner:(Also extremely fast)

最短的一个班轮:(也非常快)

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

Explanation:

解释:

  • ^\w: first character of the string
  • |: or
  • \s\w: first character after whitespace
  • (^\w|\s\w)Capture the pattern.
  • gFlag: Match all occurrences.
  • ^\w: 字符串的第一个字符
  • |: 或者
  • \s\w: 空格后的第一个字符
  • (^\w|\s\w)捕捉模式。
  • g标志:匹配所有出现。


If you want to make sure the rest is in lowercase:

如果您想确保其余部分为小写:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())