是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
如果可以的话,我强烈建议使用开源的NPM包,这个包在typescript中工作得很好:
NPM: https://www.npmjs.com/package/title-case
Github: https://github.com/blakeembrey/change-case/tree/master/packages/title-case readme
运行npm install title-case将包添加到项目中。
使用标题大小写npm包的示例代码:
import { titleCase } from "title-case";
titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
其他回答
这是我的版本,在我看来很容易理解,也很优雅。
Const STR = "foo bar baz"; const newStr = str.split(' ') .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase()) . join (' '); console.log (newStr);
https://lodash.com/docs/4.17.11#capitalize
使用Lodash库!!更可靠的
_.capitalize('FRED'); => 'Fred'
我用正则表达式回答。
更多regex信息:https://regex101.com/r/AgRM3p/1
function toTitleCase(string = '') { const regex = /^[a-z]{0,1}|\s\w/gi; string = string.toLowerCase(); string.match(regex).forEach((char) => { string = string.replace(char, char.toUpperCase()); }); return string; } const input = document.getElementById('fullname'); const button = document.getElementById('button'); const result = document.getElementById('result'); button.addEventListener('click', () => { result.innerText = toTitleCase(input.value); }); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> </head> <body> <input type="text" id="fullname"> <button id="button">click me</button> <p id="result">Result here</p> <script src="./index.js"></script> </body> </html>
不使用正则表达式,仅供参考:
String.prototype.toProperCase = function() { Var =这个。分割(' '); Var结果= []; For (var I = 0;I < words.length;我+ +){ var letter = words[i].charAt(0).toUpperCase(); 结果。Push(字母+单词[i].slice(1)); } 返回的结果。加入(' '); }; console.log ( “约翰·史密斯”.toProperCase () )
它并不短,但这是我最近在学校的一个作业中想到的:
var myPoem = '什么是jQuery,但一个误解的对象?' // jQuery不是被误解的对象吗?JQuery不是一个被误解的对象吗? / /代码 Var大写=函数(str) { var strArr = str.split(' '); var newArr = []; For (var I = 0;i < strar .length;我+ +){ newar .push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1)) }; newArr返回。加入(' ') } var fixedPoem =大写(myPoem); 警报(fixedPoem);