Javascript 将每个单词的第一个字母大写

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

Capitalize the first letter of every word

javascript

提问by David

I want to use a javascript function to capitalize the first letter of every word

我想使用 javascript 函数将每个单词的第一个字母大写

eg:

例如:

THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test

What would be a simple javascript function

什么是简单的 javascript 函数

回答by Stephen

Here's a little one liner that I'm using to get the job done

这是我用来完成工作的一个小衬垫

var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });

but John Resig did a pretty awesome script that handles a lot of cases http://ejohn.org/blog/title-capitalization-in-javascript/

但是 John Resig 做了一个非常棒的脚本,可以处理很多情况 http://ejohn.org/blog/title-capitalization-in-javascript/

Update

更新

ES6+ answer:

ES6+ 答案:

str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');

str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');

There's probably an even better way than this. It will work on accented characters.

可能还有比这更好的方法。它将适用于重音字符。

回答by reader_1000

function capitalizeEachWord(str)
{
   var words = str.split(" ");
   var arr = [];
   for (i in words)
   {
      temp = words[i].toLowerCase();
      temp = temp.charAt(0).toUpperCase() + temp.substring(1);
      arr.push(temp);
   }
   return arr.join(" ");
}

回答by Andrew D.

"tHiS iS a tESt".replace(/[^\s]+/g, function(str){ 
    return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
  });

Other variant:

其他变体:

"tHiS iS a tESt".replace(/(\S)(\S*)/g, function(
 function capitalize(str){

  var strArr = str.split(" ");
  var newArr = [];

  for(var i = 0 ; i < strArr.length ; i++ ){

    var FirstLetter = strArr[i].charAt(0).toUpperCase();
    var restOfWord = strArr[i].slice(1);

    newArr[i] = FirstLetter + restOfWord;

  }

  return newArr.join(' ');

}
,,){ return .toUpperCase()+.toLowerCase(); });

回答by DefionsCode

This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.

这是一个简单的解决方案,将句子分解成一个数组,然后循环遍历该数组,创建一个包含大写单词的新数组。

'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

回答by andersh

If you don't mind using a library, you could use Sugar.jscapitalize()

如果你不介意使用库,你可以使用Sugar.js capitalize()

capitalize( all = false )Capitalizes the first character in the string and downcases all other letters. If all is true, all words in the string will be capitalized.

capitalize( all = false )将字符串中的第一个字符大写,并将所有其他字母小写。如果全部为真,则字符串中的所有单词都将大写。

Example:

例子:

function Ucwords(str){
    var words = str.split(' ');
    var arr = [];
    words.filter(function(val){
        arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());             
    })
    console.log(arr.join(" ").trim());
    return arr.join(" ").trim();
}

Ucwords("THIS IS A TEST") //This Is A Test

Ucwords("THIS ") //This

回答by VIJAY P

you can also use below approach using filter:

您还可以使用过滤器使用以下方法:

function capitalize(str){
    str = str.toLowerCase();
    return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}

回答by Lunfel

This will capitalize every word seperated by a space or a dash

这将使由空格或破折号分隔的每个单词大写

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function () {
        return .toUpperCase();
    });
}

Examples :

例子 :

  • i lOvE oRanges => I Love Oranges
  • a strAnge-looKing syntax => A Strange-Looking Syntax
  • 我爱橙子 => 我爱橙子
  • 一个看起来很奇怪的语法 => 一个看起来很奇怪的语法

etc

等等

回答by oezi

take a look at ucwords from php.js- this seems to be kind of what you're looking for. basically, it's:

看看来自 php.js 的 ucwords- 这似乎是你正在寻找的东西。基本上,它是:

var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());

note that THIS IS A TESTwill return THIS IS A TESTso you'll have to use it like this:

请注意,THIS IS A TEST它将返回,THIS IS A TEST因此您必须像这样使用它:

function ucwords (str) {
    str = (str + '').toLowerCase();
    return str.replace(/^([a-z])|\s+([a-z])/g, function () {
        return .toUpperCase();
    });
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test

or modify the function a bit:

或者稍微修改一下函数:

##代码##