是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像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.
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?