如何使字符串的第一个字母大写,但不更改其他任何字母的大小写?
例如:
-
"this is a test"
->"This is a test"
-
"the Eiffel Tower"
->"The Eiffel Tower"
-
"/index.html"
->"/index.html"
#1楼
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
其他一些答案修改了String.prototype
(这个答案也曾经使用过),但是由于可维护性,我现在不建议这样做(很难找出将函数添加到prototype
,如果其他代码使用相同的代码,可能会导致冲突。名称/浏览器会在将来添加具有相同名称的本机功能)。
#2楼
这是一个称为ucfirst()的函数( “大写首字母”的缩写):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
您可以通过调用ucfirst(“ some string”)来大写字符串,例如,
ucfirst("this is a test") --> "This is a test"
它通过将字符串分成两部分来工作。 在第一行中,它首先提取firstLetter ,然后在第二行中,它通过调用firstLetter.toUpperCase()将大写的首字母大写 ,并将其与字符串的其余部分(通过调用str.substr (1)找到)连接起来 。
您可能会认为这将导致一个空字符串失败,而实际上在像C这样的语言中,您将不得不满足这一要求。 但是,在JavaScript中,当您接受一个空字符串的子字符串时,您只会得到一个空字符串。
#3楼
在CSS中:
p:first-letter {
text-transform:capitalize;
}
#4楼
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
(如果您经常使用它,则可以将其封装在一个函数中,甚至可以将其添加到String原型中。)
#5楼
我们可以使用我最喜欢的RegExp
来获得第一个字符,它看起来像一个可爱的笑脸: /^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
对于所有咖啡迷:
String::capitalize = ->
@replace /^./, (match) ->
match.toUpperCase()
...对于所有认为有更好方法的人,而无需扩展本机原型:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
#6楼
var string = "hello world";
string = string.charAt(0).toUpperCase() + string.slice(1);
alert(string);
#7楼
在另一种情况下,我需要将其首字母大写,将其余字母小写。 以下情况使我更改了此功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
#8楼
String.prototype.capitalize = function(allWords) {
return (allWords) ? // if all words
this.split(' ').map(word => word.capitalize()).join(' ') : //break down phrase to words then recursive calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // if allWords is undefined , capitalize only the first word , mean the first char of the whole string
}
然后:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
更新2016年11月(ES6),仅用于乐趣:
const capitalize = (string = '') => [...string].map( //convert to array with each item is a char of string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // index true means not equal 0 , so (!index) is the first char which is capitalized by `toUpperCase()` method
).join('') //return back to string
然后capitalize("hello") // Hello
#9楼
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
#10楼
如果您使用underscore.js或Lo-Dash ,则underscore.string库提供字符串扩展名,包括大写:
_.capitalize(string)将字符串的首字母转换为大写。
例:
_.capitalize("foo bar") == "Foo bar"
#11楼
使用:
var str = "ruby java"; console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将向控制台输出"Ruby java"
。
#12楼
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
#13楼
签出此解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // returns Master
#14楼
这是一种更加面向对象的方法:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
您可以像下面这样调用该函数:
"hello world".capitalize();
预期输出为:
"Hello world"
#15楼
如果您对发布的几种不同方法的性能感兴趣:
这是基于此jsperf测试的最快方法(从最快到最慢的顺序)。
如您所见,前两种方法在性能上基本上是可比的,而更改String.prototype
到目前为止是性能最慢的。
// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}
// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
return string.replace(/^./, string[0].toUpperCase());
}
// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
#16楼
如果您已经(或正在考虑)使用lodash
,则解决方案很简单:
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
_.capitalize('fred') //=> 'Fred'
查看他们的文档: https : //lodash.com/docs#capitalize
_.camelCase('Foo Bar'); //=> 'fooBar'
https://lodash.com/docs/4.15.0#camelCase
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
_.snakeCase('Foo Bar');
// => 'foo_bar'
Vanilla js的第一个大写字母:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}
#17楼
如果您这样做, ucfirst
函数将起作用。
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
感谢JP的声明。
#18楼
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
#19楼
仅CSS
p::first-letter {
text-transform: uppercase;
}
- 尽管被称为
::first-letter
,但它适用于第一个字符 ,即在字符串%a
情况下,此选择器将适用于%
,因此a
将不被大写。 - 在IE9 +或IE5.5 +中,仅使用一个冒号(
:first-letter
)的传统表示法即可支持。
ES2015单缸
由于答案很多,但ES2015中没有一个答案可以有效解决原始问题,因此我提出了以下解决方案:
const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
备注
-
parameters => function
就是所谓的箭头函数 。 - 我使用
capitalizeFirstChar
名字capitalizeFirstChar
而不是capitalizeFirstLetter
,因为OP并不要求使用代码来大写整个字符串中的第一个字母,而是大写第一个字符(当然,如果是字母)。 -
const
使我们能够将capitalizeFirstChar
声明为常量,这是需要的,因为作为程序员,您应始终明确声明您的意图。 - 在我执行的基准测试中,
string.charAt(0)
和string[0]
之间没有显着差异。 但是请注意,对于空字符串,string[0]
将是undefined
的,因此应将其重写为string && string[0]
,与替代方法相比,它太冗长了。 -
string.substring(1)
比string.slice(1)
快。
基准测试
- 此解决方案为4,956,962 ops / s±3.03%,
- 投票最多的答案为4,577,946个操作/秒±1.2%。
- 使用JSBench.me在Google Chrome 57上创建。
#20楼
通常最好先使用CSS处理这类内容,通常,如果您可以使用CSS解决某些问题,请先解决该问题,然后尝试使用JavaScript解决问题,因此在这种情况下,请尝试在CSS中使用:first-letter
应用text-transform:capitalize;
因此,尝试为此创建一个类,以便可以在全局范围内使用它,例如: .first-letter-uppercase
并在CSS中添加以下内容:
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
另外一个选择是JavaScript,因此最好是这样的:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
并这样称呼:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
如果您想一遍又一遍地重用它,最好将其附加到javascript原生String,如下所示:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
并如下调用:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'
#21楼
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
} );
};
用法:
capitalizedString = someString.capitalize();
这是一个文本字符串=>这是一个文本字符串
#22楼
你可以像这样一行
string[0].toUpperCase() + string.substring(1)
#23楼
这是2018 ECMAScript 6+解决方案 :
const str = 'the Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
#24楼
yourString.replace(/\w/, c => c.toUpperCase())
我发现此箭头功能最简单。 Replace匹配字符串的第一个字母字符( \\w
),并将其转换为大写。 不需要任何爱好者。
#25楼
最短的 3个解决方案,1和2处理s
字符串为""
, null
和undefined
:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
let s='foo bar'; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&&s.replace(/./,s[0].toUpperCase()) ); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
#26楼
有一个非常简单的方法可以通过replace实现它。 对于ECMAScript 6:
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'
#27楼
如果要重新格式化全部大写的文本,则可能需要修改其他示例,例如:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
这将确保更改以下文本:
TEST => Test
This Is A TeST => This is a test
#28楼
这是流行答案的简化版本,它通过将字符串视为数组来获得第一个字母:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
更新:
根据下面的评论,这在IE 7或更低版本中不起作用。
更新2:
为了避免undefined
空字符串(请参见下面的@ njzk2的注释 ),您可以检查一个空字符串:
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
#29楼
将字符串中所有单词的首字母大写:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
#30楼
在CSS中似乎更容易:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>