是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。


当前回答

这是一行解决方案,如果你想转换字符串中的每个工作,用“”分割字符串,遍历部分并将此解决方案应用到每个部分,将每个转换的部分添加到一个数组中,并与“”连接。

var stringToConvert='john'; stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join(''); console.log(stringToConvert);

其他回答

以“lewax00”解决方案为例,我创建了这个简单的解决方案,强制以空格开头的“w”或初始化de word的“w”,但无法删除额外的中间空格。

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt){返回txt. touppercase ();});

结果是“Sofía Vergara”。

如果你想使用NPM库,请查看title-case:

安装:

npm install title-case --save

用法:

import { titleCase } from "title-case";

titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"

ES 6

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

else

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')

一种方法使用减少

函数titleCase(str) { Const arr = str.split(" "); Const result = arr。Reduce ((acc, cur) => { const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase(); 返回${newStr} }, " ") 返回的结果。片(0,result.length-1); }

瓦尔·弦=“测试” 笨蛋。 var输出=弦。charAt(0) 控制台日志(输出)。 警报(输出)

  
 var string = "tEsT"

 string = string.toLowerCase() 

 string.charAt(0).toUpperCase() + string.slice(1)

string.charAt(0) returns the character at the 0th index of the string. toUpperCase() is a method that returns the uppercase equivalent of a string. It is applied to the first character of the string, returned by charAt(0). string.slice(1) returns a new string that starts from the 1st index (the character at index 0 is excluded) till the end of the string. Finally, the expression concatenates the result of toUpperCase() and string.slice(1) to create a new string with the first character capitalized.