如何使字符串的第一个字母大写,但不更改其他任何字母的大小写?
例如:
"this is a test"
->"This is a test"
"the Eiffel Tower"
->"The Eiffel Tower"
"/index.html"
->"/index.html"
如何使字符串的第一个字母大写,但不更改其他任何字母的大小写?
例如:
"this is a test"
-> "This is a test"
"the Eiffel Tower"
-> "The Eiffel Tower"
"/index.html"
-> "/index.html"
yourString.replace(/\w/, c => c.toUpperCase())
I found this arrow function easiest. Replace matches the first letter character (\w
) of your string and converts it to uppercase. Nothing fancier necessary.
The ucfirst
function works if you do it like this.
function ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
Thanks J-P for the aclaration.
yourString.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
(You may encapsulate it in a function or even add it to the String prototype if you use it frequently.)
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
} );
};
Usage:
capitalizedString = someString.capitalize();
This is a text string => This Is A Text String
Here is a function called ucfirst() (short for "upper case first letter"):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
You can capitalise a string by calling ucfirst("some string") -- for example,
ucfirst("this is a test") --> "This is a test"
It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).
You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in JavaScript, when you take a substring of an empty string, you just get an empty string back.
If you are wanting to reformat all-caps text, you might want to modify the other examples as such:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
This will ensure that the following text is changed:
TEST => Test
This Is A TeST => This is a test
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
采用:
var str = "ruby java";
console.log(str.charAt(0).toUpperCase() + str.substring(1));
它将输出"Ruby java"
到控制台。
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"
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
我们可以得到第一个我最喜欢的角色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();
});
};
如果您使用underscore.js或Lo-Dash,则underscore.string库提供字符串扩展名,包括大写:
_.capitalize(string)将字符串的首字母转换为大写。
例:
_.capitalize("foo bar") == "Foo bar"
将字符串中所有单词的首字母大写:
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(" ");
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
修改了其他一些答案String.prototype
(这个答案也曾经使用过),但是由于可维护性,我现在建议这样做(很难找出将函数添加到的位置prototype
,如果其他代码使用相同的名称/浏览器,则可能导致冲突将来添加具有相同名称的本机函数)。
这是流行答案的简化版本,它通过将字符串视为数组来获得第一个字母:
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);
}
在另一种情况下,我需要将其首字母大写,将其余字母小写。以下情况使我更改了此功能:
//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();
这是一种更加面向对象的方法:
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
您可以像下面这样调用该函数:
"hello world".capitalize();
预期输出为:
"Hello world"
这是基于此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);
}
在CSS中:
p:first-letter {
text-transform:capitalize;
}
You can do it in one line like this