是否有一个简单的方法来转换字符串标题大小写?例如,约翰·史密斯变成了约翰·史密斯。我不是在寻找像John Resig的解决方案那样复杂的东西,只是(希望)一些一两行代码。
当前回答
瓦尔·弦=“测试” 笨蛋。 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.
其他回答
不使用正则表达式,仅供参考:
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 () )
试试这个
String.prototype.toProperCase = function(){
return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g,
function($1){
return $1.toUpperCase();
}
);
};
例子
var str = 'john smith';
str.toProperCase();
这是一行解决方案,如果你想转换字符串中的每个工作,用“”分割字符串,遍历部分并将此解决方案应用到每个部分,将每个转换的部分添加到一个数组中,并与“”连接。
var stringToConvert='john'; stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join(''); console.log(stringToConvert);
这是我的版本,在我看来很容易理解,也很优雅。
Const STR = "foo bar baz"; const newStr = str.split(' ') .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase()) . join (' '); console.log (newStr);
function toTitleCase(str) {
var strnew = "";
var i = 0;
for (i = 0; i < str.length; i++) {
if (i == 0) {
strnew = strnew + str[i].toUpperCase();
} else if (i != 0 && str[i - 1] == " ") {
strnew = strnew + str[i].toUpperCase();
} else {
strnew = strnew + str[i];
}
}
alert(strnew);
}
toTitleCase("hello world how are u");
推荐文章
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()