在字符串中大写单词的最佳方法是什么?
当前回答
用这个:
String.prototype.toTitleCase = function() { 返回this.charAt(0).toUpperCase() + this.slice(1); } 让STR = 'text'; document.querySelector(#演示)。innerText = str.toTitleCase(); <div class = "app"> <p id = "demo"></p> . < / div >
其他回答
Jquery或Javascipt没有提供内置方法来实现这一点。
CSS测试转换(text-transform:capitalize;)并不真正大写字符串的数据,而是在屏幕上显示一个大写的渲染。
如果您正在使用普通的香草ajs在数据级别上寻找一种更合法的方法来实现这一点,请使用这个解决方案=>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/\s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
用这个:
String.prototype.toTitleCase = function() { 返回this.charAt(0).toUpperCase() + this.slice(1); } 让STR = 'text'; document.querySelector(#演示)。innerText = str.toTitleCase(); <div class = "app"> <p id = "demo"></p> . < / div >
我将使用regex来实现这个目的:
myString = ' this Is my sTring. ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
使用JavaScript和html
String.prototype.capitalize = function() { 返回this.replace (/ (^ | \ s) ([a - z]) / g函数(m, p1, p2) { return p1 + p2.toUpperCase(); }); }; <form name="form1" method="post"> <input name="instring" type="text" value="this is the text string" size="30"> <input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();" > <input name="outstring" type="text" value="" size="30"> > < /形式
基本上,你可以用string。capitalize()它会大写每个单词的第一个字母。
来源:http://www.mediacollege.com/internet/javascript/text/case-capitalize.html
在字符串中大写单词的最短实现是使用ES6的箭头函数:
'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'
ES5兼容实现:
'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'
regex基本上匹配给定字符串中每个单词的首字母,并只将该字母转换为大写字母:
\b匹配单词边界(单词的开头或结尾); \w匹配下面的元字符[a-zA-Z0-9]。
对于非ascii字符,请参考此解决方案
'ÿöur striñg'.replace(/(^|\s)\S/g, l => l.toUpperCase())
这个正则表达式匹配给定字符串中的第一个字母和前面有空格的每个非空格字母,并只将该字母转换为大写字母:
\s匹配一个空白字符 \S匹配非空格字符 (x|y)匹配任何指定的替代项
这里可以使用非捕获组,如下所示/(?:^|\s)\ s /g,尽管正则表达式中的g标志不会按设计捕获子组。